﻿///<jscompress sourcefile="CesiumEcefLlhEnu.js" />

/*  *  *  *  *  *  *  *  *  *  *
 *     对cesium分析的扩展      *
 *  *  *  *  *  *  *  *  *  *  */
!function(e, t) {
	"object" == typeof exports && "object" == typeof module ? module.exports = t(require("Cesium"))
			: "function" == typeof define && define.amd ? define([ "Cesium" ],
					t)
					: "object" == typeof exports ? exports.CesiumAnalysi = t(require("Cesium"))
							: e.CesiumAnalysi = t(e.Cesium)
}("undefined" != typeof self ? self : this, function(cesium) {
	function _() {
	    this.PI = 3.141592653589793238;
	    this.a = 6378137.0;
	    this.b = 6356752.3142
	    this.f = (this.a - this.b) / this.a;
	    this.e_sq = this.f * (2.0 - this.f);
	    this.ee = 0.00669437999013;
	    this.WGSF = 1 / 298.257223563;
	    this.WGSe2 = this.WGSF * (2 - this.WGSF);
	    this.WGSa = 6378137.00000;
	    this.EPSILON = 1.0e-12;
	}
	 _.prototype.CalculateCoordinates = function (point, azimuth, elevation, distance) {
	    var vertical_height = distance * Math.sin(2 * this.PI / 360 * elevation);//垂直高度
	    var  horizontal_distance = distance * Math.cos(2 * this.PI / 360 * elevation);//水平距离
	    if (azimuth > 360) azimuth = azimuth % 360;
	    if (azimuth < 0) azimuth = 360 + (azimuth % 360);

	    var point = this.lonLat2WebMercator(point);
	    var lnglat = null;

	    if (azimuth <= 90) {//第四象限
	    	var x_length = horizontal_distance * Math.cos(2 * this.PI / 360 * azimuth);
	    	var y_length = horizontal_distance * Math.sin(2 * this.PI / 360 * azimuth);
	        lnglat = {
	            x: point.x + x_length,
	            y: point.y - y_length
	        }
	    } else if (azimuth > 90 && azimuth <= 180) {//第三象限
	    	var x_length = horizontal_distance * Math.sin(2 * this.PI / 360 * (azimuth - 90));
	    	var y_length = horizontal_distance * Math.cos(2 * this.PI / 360 * (azimuth - 90));
	        lnglat = {
	            x: point.x - x_length,
	            y: point.y - y_length
	        }
	    } else if (azimuth > 180 && azimuth <= 270) {//第二象限
	    	var x_length = horizontal_distance * Math.cos(2 * this.PI / 360 * (azimuth - 180));
	    	var y_length = horizontal_distance * Math.sin(2 * this.PI / 360 * (azimuth - 180));
	        lnglat = {
	            x: point.x - x_length,
	            y: point.y + y_length
	        }
	    } else {//第一象限
	    	var x_length = horizontal_distance * Math.sin(2 * this.PI / 360 * (azimuth - 270));
	    	var y_length = horizontal_distance * Math.cos(2 * this.PI / 360 * (azimuth - 270));
	        lnglat = {
	            x: point.x + x_length,
	            y: point.y + y_length
	        }
	    }
	    lnglat = this.webMercator2LonLat(lnglat);
	    return {
	        lng: lnglat.x,
	        lat: lnglat.y,
	        height: vertical_height
	    }
	}
	 /*
	    *经纬度转Web墨卡托
	    *@lonLat 经纬度
	    */
	 _.prototype.lonLat2WebMercator = function (lonLat) {
	    let x = lonLat.x * this.a / 180;
	    let y = Math.log(Math.tan((90 + lonLat.y) * this.PI / 360)) / (this.PI / 180);
	    y = y * this.a / 180;
	    return {
	        x: x,
	        y: y
	    }
	}
	 
	 /*
	    *Web墨卡托转经纬度
	    *@mercator 平面坐标
	    */
	_.prototype.webMercator2LonLat = function (mercator) {
	    let x = mercator.x / this.a * 180;
	    let y = mercator.y / this.a * 180;
	    y = 180 / this.PI * (2 * (Math.exp(y * this.PI / 180)) - this.PI / 2);
	    return {
	        x: x,
	        y: y
	    }
	}

	_.prototype.get_atan = function (z, y) {
	    let x;
	    if (z == 0) {
	        x = this.PI / 2;
	    } else {
	        if (y == 0) {
	            x = this.PI;
	        } else {
	            x = Math.atan(Math.abs(y / z));
	            if ((y > 0) && (z < 0)) {
	                x = this.PI - x;
	            } else if ((y < 0) && (z < 0)) {
	                x = this.PI + x;
	            } else if ((y < 0) && (z > 0)) {
	                x = 2 * this.M_PI - x;
	            }
	        }
	    }
	    return x;
	}
	//WGS84转ECEF坐标系
	_.prototype.ConvertLLAToXYZ = function (LLACoor) {
	    let lon = this.PI / 180 * LLACoor.longitude;
	    let lat = this.PI / 180 * LLACoor.latitude;
	    let H = LLACoor.altitude;
	    let N0 = this.a / Math.sqrt(1.0 - this.ee * Math.sin(lat) * Math.sin(lat));
	    let x = (N0 + H) * Math.cos(lat) * Math.cos(lon);
	    let y = (N0 + H) * Math.cos(lat) * Math.sin(lon);
	    let z = (N0 * (1.0 - this.ee) + H) * Math.sin(lat);
	    return {
	        x: x,
	        y: y,
	        z: z
	    }
	}

	//ECEF坐标系转WGS84
	_.prototype.ConvertXYZToLLA = function (XYZCoor) {
	    let longitude = this.get_atan(XYZCoor.x, XYZCoor.y);
	    if (longitude < 0) {
	        longitude = longitude + this.PI;
	    }
	    let latitude = this.get_atan(Math.sqrt(XYZCoor.x * XYZCoor.x + XYZCoor.y * XYZCoor.y), XYZCoor.z);

	    let W = Math.sqrt(1 - this.WGSe2 * Math.sin(latitude) * Math.sin(latitude));
	    let N = this.WGSa / W;
	    let B1;
	    do {
	        B1 = latitude;
	        W = Math.sqrt(1 - this.WGSe2 * Math.sin(B1) * Math.sin(B1));
	        N = this.WGSa / W;
	        latitude = this.get_atan(Math.sqrt(XYZCoor.x * XYZCoor.x + XYZCoor.y * XYZCoor.y), (XYZCoor.z + N * this.WGSe2 * Math.sin(B1)));
	    }
	    while (Math.abs(latitude - B1) > this.EPSILON);

	    altitude = Math.sqrt(XYZCoor.x * XYZCoor.x + XYZCoor.y * XYZCoor.y) / Math.cos(latitude) - this.WGSa / Math.sqrt(1 - this.WGSe2 * Math.sin(latitude) * Math.sin(latitude));

	    return {
	        longitude: longitude * 180 / this.PI,
	        latitude: latitude * 180 / this.PI,
	        altitude: altitude
	    }
	}
	/*北东天坐标系转WGS84
	@ a A点坐标
	@ p 相对参数，距离、方位角、仰角
	*/
		//	俯视角pitch -elevation 
	//航向角heading（yaw） -azimuth 
	_.prototype.enu_to_ecef = function (a, p) {
	    //距离
	    let distance = p.distance;
	    //方位角
	    let azimuth = p.azimuth;
	    //仰角
	    let elevation = p.elevation;

	    let zUp = elevation >= 0 ? distance * Math.sin(this.PI / 180 * elevation) : (-1) * distance * Math.sin(this.PI / 180 * Math.abs(elevation));

	    let d = distance * Math.cos(this.PI / 180 * Math.abs(elevation));
	    let xEast;
	    let yNorth;
	    if (azimuth <= 90) {
	        xEast = d * Math.sin(this.PI / 180 * azimuth);
	        yNorth = d * Math.cos(this.PI / 180 * azimuth);
	    } else if (azimuth > 90 && azimuth < 180) {
	        xEast = d * Math.cos(this.PI / 180 * (azimuth - 90));
	        yNorth = (-1)*d * Math.sin(this.PI / 180 * (azimuth - 90));
	    } else if (azimuth > 180 && azimuth < 270) {
	        xEast = (-1) * d * Math.sin(this.PI / 180 * (azimuth - 180));
	        yNorth =(-1) *  d * Math.cos(this.PI / 180 * (azimuth - 180));
	    } else {
	        xEast = (-1) * d * Math.sin(this.PI / 180 * (360 - azimuth));
	        yNorth =  d * Math.cos(this.PI / 180 * (360 - azimuth));
	    }

	    let lamb = this.radians(a.latitude);
	    let phi = this.radians(a.longitude);
	    let h0 = a.altitude;

	    let s = Math.sin(lamb);
	    let N = this.a / Math.sqrt(1.0 - this.e_sq * s * s);

	    let sin_lambda = Math.sin(lamb);
	    let cos_lambda = Math.cos(lamb);

	    let sin_phi = Math.sin(phi);
	    let cos_phi = Math.cos(phi);

	    let x0 = (h0 + N) * cos_lambda * cos_phi;
	    let y0 = (h0 + N) * cos_lambda * sin_phi;
	    let z0 = (h0 + (1 - this.e_sq) * N) * sin_lambda;

	    let t = cos_lambda * zUp - sin_lambda * yNorth;

	    let zd = sin_lambda * zUp + cos_lambda * yNorth;
	    let xd = cos_phi * t - sin_phi * xEast;
	    let yd = sin_phi * t + cos_phi * xEast;

	    return this.ConvertXYZToLLA({
	        x: xd + x0,
	        y: yd + y0,
	        z: zd + z0
	    })
	}
	_.prototype.radians = function (degree) {
	    return this.PI / 180 * degree;
	}	 
	cesium.ECEF = _;
})

;
///<jscompress sourcefile="VFG.js" />
if (!window.VFG) {
  window.VFG = {};
}
var VFG = window.VFG;
VFG.Map = function(domId,options) {
	this.objects=new Map();
	this.ImageryLayerMap=new Map();//底图集合
	this.tilesetLayerMap=new Map();//底图集合
	this.modelLayerMap=new Map();//底图集合
	this.vmodelLayerMap=new Map();//底图集合
	this.entityLayerMap=new Map();//底图集合
	this.pointLayerMap=new Map();//底图集合
	this.collectionLayerMap=new Map();//底图集合
	this.polylineLayerMap=new Map();//底图集合
	this.measureLayerMap=new Map();//测量集合
	this.wallLayerMap=new Map();//测量集合
	
	let param={
			scene3DOnly:options.scene3DOnly||true,
			selectionIndicator: options.selectionIndicator||false,
			baseLayerPicker:options.baseLayerPicker||false,
			animation: options.animation||false,
			timeline: options.timeline||false,
			navigationHelpButton: options.navigationHelpButton||false,
			fullscreenButton: options.fullscreenButton||false,
			geocoder:options.geocoder||false,
			homeButton:options.homeButton||false,
			shouldAnimate: options.shouldAnimate||false,
			sceneModePicker: options.sceneModePicker||false,
			shouldAnimate:options.shouldAnimate||false,
			infoBox: options.infoBox||false,
			sceneMode: options.sceneMode || Cesium.SceneMode.SCENE2D,	
			clockViewModel:new Cesium.ClockViewModel(),
	};
	
	if(options.scene){
		param.scene={
			center:options.scene.center,
			showSun:options.scene.showSun||true,
			showMoon:options.scene.showMoon||true,
			showSkyAtmosphere:options.scene.showSkyAtmosphere||true,
			fog:options.scene.fog||true,
			fxaa:options.scene.fxaa||true,
			showSkyBox:options.scene.showSkyBox||true,
		}
		if(options.scene.skyBox && options.scene.skyBox.length==6){
			param.scene.skyBox=new Cesium.SkyBox({
	    	  sources: {
				  positiveX: skyBox[0],
				  negativeX: skyBox[1],
				  positiveY: skyBox[2],
				  negativeY: skyBox[3],
				  positiveZ: skyBox[4],
				  negativeZ: skyBox[5]
	    	  	}
    	  });
		}
		if(options.scene.globe){
			param.scene.globe={
				depthTestAgainstTerrain:options.scene.globe.depthTestAgainstTerrain||true,
				baseColor:options.scene.globe.baseColor||null,
			}
		}
		if(options.scene.cameraController){
			param.scene.cameraController={
				zoomFactor:options.scene.cameraController.zoomFactor||3,
				minimumZoomDistance:options.scene.cameraController.minimumZoomDistance||0,
				maximumZoomDistance:options.scene.cameraController.maximumZoomDistance||50000000,
				enableRotate:options.scene.cameraController.enableRotate||true,
				enableZoom:options.scene.cameraController.enableZoom||true,
			}
		}
	}
	
	if(options.contextOptions){
		param.contextOptions={}
		if(options.contextOptions.webgl){
			param.contextOptions.webgl={
				alpha:options.contextOptions.webgl.alpha||true,
				depth:options.contextOptions.webgl.depth||true,
				stencil:options.contextOptions.webgl.stencil||true,
				antialias:options.contextOptions.webgl.antialias||true,
				premultipliedAlpha:options.contextOptions.webgl.premultipliedAlpha||true,
				preserveDrawingBuffer:options.contextOptions.webgl.preserveDrawingBuffer||true,
				failIfMajorPerformanceCaveat:options.contextOptions.webgl.failIfMajorPerformanceCaveat||true,
			}
		}
	}
    
	param.imageryProvider=new Cesium.TileMapServiceImageryProvider({
		url:"assets/plugins/Cesium/Assets/Textures/NaturalEarthII",
		maximumLevel: 1,
	})
	
	Cesium.Ion.defaultAccessToken ="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJiZjliY2NhNS1iMThiLTQzZTYtOWM1ZS03NDMxMmY3YjIyNmUiLCJpZCI6MjAwNDcsInNjb3BlcyI6WyJhc2wiLCJhc3IiLCJhc3ciLCJnYyJdLCJpYXQiOjE1ODMxOTk3NTl9.lzdqsXU24bvovmmaRPXcD3jmSH0WmYTwmX6isCx8qfA";
	this.viewer = new Cesium.Viewer(domId,param);
	this.viewer.cesiumWidget.creditContainer.style.display = "none";
	this.viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
	this.viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
	
	//Cesium 禁止/允许相机进入地下
	this.viewer.scene.screenSpaceCameraController.enableCollisionDetection = false; //true 禁止 false 允许
	
	//解决模糊问题
	if(Cesium.FeatureDetection.supportsImageRenderingPixelated()){//判断是否支持图像渲染像素化处理
		this.viewer.resolutionScale = window.devicePixelRatio;
	}
	//是否开启抗锯齿
	this.viewer.scene.fxaa = true;
	this.viewer.scene.postProcessStages.fxaa.enabled = true;
	
	
	
	
//	this.viewer._cesiumWidget._supportsImageRenderingPixelated = Cesium.FeatureDetection.supportsImageRenderingPixelated();
//	this.viewer._cesiumWidget._forceResize = true;
//	if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {
//	    var vtxf_dpr = window.devicePixelRatio;
//	    // 适度降低分辨率
//	    while (vtxf_dpr >= 2.0) {
//	        vtxf_dpr /= 2.0;
//	    }
//	    this.viewer.resolutionScale = vtxf_dpr;
//	}
	
	

//	this.viewer.scene.globe.enableLighting = true; //关闭光照
//	this.viewer.scene.sun.true = 5; //太阳变大
//	this.viewer.shadows = true;//关闭阴影
//    this.viewer.scene.light = new Cesium.DirectionalLight({ //去除时间原因影响模型颜色
//    	  direction: new Cesium.Cartesian3(0.354925, -0.890918, -0.283358)
//    });
	
    this.viewer.scene.skyBox.show = false; 

    
    // 亮度设置
//    var stages = this.viewer.scene.postProcessStages;
//    this.viewer.scene.brightness =  this.viewer.scene.brightness || stages.add(Cesium.PostProcessStageLibrary.createBrightnessStage());
//    this.viewer.scene.brightness.enabled = true;
//    this.viewer.scene.brightness.uniforms.brightness = Number(1.0);
    
    
	this.viewer.scene.primitives.add(new Cesium.PointPrimitiveCollection(),0);
	this.viewer.scene.primitives.add(new Cesium.LabelCollection(),1);
	this.viewer.scene.primitives.add(new Cesium.BillboardCollection(),2);
	
//	 var collection = this.viewer.scene.postProcessStages;
//	 var silhouette = collection.add(Cesium.PostProcessStageLibrary.createBrightnessStage());
//	 silhouette.enabled = true;
//	silhouette.uniforms.brightness=1;// （调节亮度0-3最佳）
	let _this=this;
	this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
    this.handler.setInputAction(function (movement) {
    	if(Cesium.defined(_this.mouseMoveFun)){
    		_this.mouseMoveFun(movement);
    	}
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
	
	return this;
}

/**
 * 获取主键ID
 */
VFG.Map.prototype.getUuid = function() {
	return VFG.Util.getUuid();
};

/**
 * 将三维球定位到中国
 */
VFG.Map.prototype.flyToChina = function(complete) {
	this.viewer.camera.flyTo({
	    destination: Cesium.Cartesian3.fromDegrees(103.84, 31.15, 17850000),
	    orientation: {
	        heading :  Cesium.Math.toRadians(348.4202942851978),
	        pitch : Cesium.Math.toRadians(-89.74026687972041),
	        roll : Cesium.Math.toRadians(0)
	    },
	    complete:function callback() {
	    	if(complete){
	    		complete();
	    	}
	    }
	});
}

VFG.Map.prototype.openFlyAnimation=function(param) {
    var that = this;
    var viewer = this.viewer;
    var view = this.getCameraView(); //默认为原始视角
    
    var position=param.position;
    var orientation=param.orientation||{};

    if(!position){
    	return;
    }
    
    viewer.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(-85.16, 13.71, 23000000.0),
    });
    
    viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(position.x, position.y, 23000000.0),
        duration: 2,
        easingFunction: Cesium.EasingFunction.LINEAR_NONE,
        complete: function complete() {
            var z = Cesium.defaultValue(position.z, 90000);
            if (z < 200000 && orientation.pitch != -90) {
                z = z * 1.5 + 8000;
                viewer.camera.flyTo({
                    destination: Cesium.Cartesian3.fromDegrees(position.x, position.y, z),
                    complete: function complete() {
                    	viewer.camera.flyTo({
                            destination : Cesium.Cartesian3.fromDegrees(position.x*1, position.y*1,position.z*1),
                            orientation : {
                                heading : Cesium.Math.toRadians(orientation.pitch?orientation.heading*1:0),
                                pitch : Cesium.Math.toRadians(orientation.pitch?orientation.pitch*1:0),
                                roll :Cesium.Math.toRadians(orientation.pitch?orientation.roll*1:0)
                            },
	                    	complete: function complete() {
	                            that._isFlyAnimation = false;
	                            if (param.complete) param.complete();
	                        }
                        });
                    }
                });
            } else {
            	viewer.camera.flyTo({
                    destination : Cesium.Cartesian3.fromDegrees(position.x*1, position.y*1,position.z*1),
                    orientation : {
                        heading : Cesium.Math.toRadians(orientation.pitch?orientation.heading*1:0),
                        pitch : Cesium.Math.toRadians(orientation.pitch?orientation.pitch*1:0),
                        roll :Cesium.Math.toRadians(orientation.pitch?orientation.roll*1:0)
                    },
                	complete: function complete() {
                        that._isFlyAnimation = false;
                        if (param.complete) param.complete();
                    }
                });
            }
        }
    });
}

//提取相机视角范围参数 
VFG.Map.prototype.getCameraView=function() {
    var camera = this.viewer.camera;
    var position = camera.positionCartographic;
    var bookmark = {};
    bookmark.y = VFG.Util.formatNum(Cesium.Math.toDegrees(position.latitude), 6);
    bookmark.x = VFG.Util.formatNum(Cesium.Math.toDegrees(position.longitude), 6);
    bookmark.z = VFG.Util.formatNum(position.height, 2);
    bookmark.heading = VFG.Util.formatNum(Cesium.Math.toDegrees(camera.heading || -90), 1);
    bookmark.pitch = VFG.Util.formatNum(Cesium.Math.toDegrees(camera.pitch || 0), 1);
    bookmark.roll = VFG.Util.formatNum(Cesium.Math.toDegrees(camera.roll || 0), 1);
    return bookmark;
}

/**
 * 渲染对象
 */
VFG.Map.prototype.render = function(option,uri) {
	if(option && '0'==option.type){
		if(!this.ImageryLayerMap.has(option.id)){
			let entity=VFG.Render.getImageryProvider(this.viewer,option,uri);
			this.ImageryLayerMap.set(option.id,entity);
			return entity;
		}
	}
	else if(option && '1'==option.type){
		if(!this.tilesetLayerMap.has(option.id)){
			let entity=VFG.Render.getTModel(this.viewer,option,uri);
			this.tilesetLayerMap.set(option.id,entity);
			return entity;
		}
	}
	else if(option && '2'==option.type){
		if(!this.modelLayerMap.has(option.id)){
			let entity=VFG.Render.getPModel(this.viewer,option,uri);
			this.modelLayerMap.set(option.id,entity);
			return entity;
		}
	}
	else if(option && '3'==option.type){
		if(!this.vmodelLayerMap.has(option.id)){
			let entity=VFG.Render.getVModel(this.viewer,option,uri);
			this.vmodelLayerMap.set(option.id,entity);
			return entity;
		}
	}
	else if(option && 'ERoadMark'==option.type){
		if(!this.entityLayerMap.has(option.id)){
			let entity=VFG.Render.getERoadMark(this.viewer,option,uri);
			this.entityLayerMap.set(option.id,entity);
			return entity;
		}
	}
	else if(option && 'Point'==option.type){
		if(!this.pointLayerMap.has(option.id)){
			let entity=VFG.Render.getPointMark(this.viewer,option,uri);
			this.pointLayerMap.set(option.id,entity);
			return entity;
		}
	}
	else if(option && 'Polyline'==option.type){
		if(!this.polylineLayerMap.has(option.id)){
			let entity=VFG.Render.getEPolyline(this.viewer,option,uri);
			this.polylineLayerMap.set(option.id,entity);
			return entity;
		}
	}
	else if(option && 'Wall'==option.type){
		if(!this.wallLayerMap.has(option.id)){
			let entity=VFG.Render.getEWall(this.viewer,option,uri);
			this.wallLayerMap.set(option.id,entity);
			return entity;
		}
	}
}

VFG.Map.prototype.renders = function(list,uri) {
	for(var item of list){
		this.render(item,uri);
	}
}

/**
 * 添加点点集合
 */
VFG.Map.prototype.addPointToLayer= function(obj) {
	if(!this.pointLayerMap.has(obj.id)){
		this.pointLayerMap.set(obj.id,obj)
	}	
}

/**
 * 获取对象
 */
VFG.Map.prototype.getById = function(id) {
	if(this.objects.has(id)){
		return this.objects.get(id);
	}
	else if(this.tilesetLayerMap.has(id)){
		return this.tilesetLayerMap.get(id);
	}
	else if(this.ImageryLayerMap.has(id)){
		return this.ImageryLayerMap.get(id);
	}
	else if(this.modelLayerMap.has(id)){
		return this.modelLayerMap.get(id);
	}
	else if(this.vmodelLayerMap.has(id)){
		return this.vmodelLayerMap.get(id);
	}
	else if(this.entityLayerMap.has(id)){
		return this.entityLayerMap.get(id);
	}
	else if(this.pointLayerMap.has(id)){
		return this.pointLayerMap.get(id);
	}
	else if(this.polylineLayerMap.has(id)){
		return this.polylineLayerMap.get(id);
	}
}

/**
 * 移除对象
 */
VFG.Map.prototype.remove = function(id) {
	if(this.objects.has(id)){
		try{
			this.objects.get(id).destroy();
		}catch (e) {
		}finally{
			this.objects.delete(id);
		}
	}
	else if(this.ImageryLayerMap.has(id)){
		try{
			this.ImageryLayerMap.get(id).destroy();
		}catch (e) {
		}finally{
			this.ImageryLayerMap.delete(id);
		}
	}
	else if(this.tilesetLayerMap.has(id)){
		try{
			this.tilesetLayerMap.get(id).destroy();
		}catch (e) {
		}finally{
			this.tilesetLayerMap.delete(id);
		}
	}
	else if(this.modelLayerMap.has(id)){
		try{
			this.modelLayerMap.get(id).destroy();
		}catch (e) {
		}finally{
			this.modelLayerMap.delete(id);
		}
	}
	else if(this.vmodelLayerMap.has(id)){
		try{
			this.vmodelLayerMap.get(id).destroy();
		}catch (e) {
		}finally{
			this.vmodelLayerMap.delete(id);
		}
	}
	else if(this.entityLayerMap.has(id)){
		try{
			this.entityLayerMap.get(id).destroy();
		}catch (e) {
		}finally{
			this.entityLayerMap.delete(id);
		}
	}
	else if(this.pointLayerMap.has(id)){
		try{
			this.pointLayerMap.get(id).destroy();
		}catch (e) {
		}finally{
			this.pointLayerMap.delete(id);
		}
	}
	else if(this.polylineLayerMap.has(id)){
		try{
			this.polylineLayerMap.get(id).destroy();
		}catch (e) {
		}finally{
			this.polylineLayerMap.delete(id);
		}
	}
}

VFG.Map.prototype.removes = function(list) {
	for(let item of list){
		this.remove(item.id);
	}
}

/**
 * 清空
 */
VFG.Map.prototype.clearAll = function() {
	_this=this;
	_this.objects.forEach(function (value,key){
		try{
			_this.objects.get(key).destroy();
		}catch (e) {
		}
	});
	_this.objects.clear();
	_this.ImageryLayerMap.forEach(function (value,key){
		try{
			_this.ImageryLayerMap.get(key).destroy();
		}catch (e) {
		}
	});
	_this.ImageryLayerMap.clear();
	
	_this.modelLayerMap.forEach(function (value,key){
		try{
			_this.modelLayerMap.get(key).destroy();
		}catch (e) {
		}
	});
	_this.modelLayerMap.clear();
	
	_this.tilesetLayerMap.forEach(function (value,key){
		try{
			_this.tilesetLayerMap.get(key).destroy();
		}catch (e) {
		}
	});
	_this.tilesetLayerMap.clear();
	
	_this.vmodelLayerMap.forEach(function (value,key){
		try{
			_this.vmodelLayerMap.get(key).destroy();
		}catch (e) {
		}
	});
	_this.vmodelLayerMap.clear();
	
	_this.entityLayerMap.forEach(function (value,key){
		try{
			_this.entityLayerMap.get(key).destroy();
		}catch (e) {
		}
	});
	_this.entityLayerMap.clear();
	
	_this.polylineLayerMap.forEach(function (value,key){
		try{
			_this.polylineLayerMap.get(key).destroy();
		}catch (e) {
		}
	});
	_this.polylineLayerMap.clear();
	
}


VFG.Map.prototype.exportToImg=function(width,height){
	return VFG.Util.exportToImg(this.viewer,width,height);
}


/**
 * 绘制模型
 */
VFG.Map.prototype.drawPModel = function(option) {
	return new VFG.DrawPModel( this.viewer,option);
}

VFG.Map.prototype.createEditPModel = function(entity) {
	return new VFG.EditPModel(this.viewer,entity);
}

VFG.Map.prototype.createEditRoadMark = function(entity) {
	return new VFG.EditRoadMark(this.viewer,entity);
}

/**
 * 绘制视频模型
 */
VFG.Map.prototype.drawVModel = function(option) {
	return new VFG.DrawVModel( this.viewer,option);
}

VFG.Map.prototype.createEditVModel = function(entity) {
	return new VFG.EditVModel(this.viewer,entity);
}

/**
 * 绘制路面标注
 */
VFG.Map.prototype.drawRoadMark = function(option) {
	return new VFG.DrawRoadMark(this.viewer,option);
}



/**
 * 绘制点
 */
VFG.Map.prototype.drawPPoint = function(option) {
	return new VFG.DrawPPoint(this.viewer,option);
}

/**
 *编辑点 
 */
VFG.Map.prototype.createEditPPoint = function(option) {
	return new VFG.EditPPoint(this.viewer,option);
}

VFG.Map.prototype.createEditTModel = function(entity) {
	return new VFG.EditTModel(this.viewer,entity);
}

/**
 * 绘制矩形
 */
VFG.Map.prototype.drawRectangle = function(option) {
	return new VFG.DrawRectangle(this.viewer,option);
}

VFG.Map.prototype.drawPolyline = function(option) {
	return new VFG.DrawPolyline(this.viewer,option);
}

VFG.Map.prototype.createEditEPolyline = function(entity) {
	return new VFG.EditEPolyline(this.viewer,entity);
}

VFG.Map.prototype.drawPolygon = function(option) {
	return new VFG.DrawPolygon(this.viewer,option);
}

VFG.Map.prototype.drawWall = function(option) {
	return new VFG.DrawWall(this.viewer,option);
}

/**
 * 空间距离测量
 */
VFG.Map.prototype.measureLength = function() {
	let entity = new VFG.MeasureLength( this.viewer);
	this.measureLayerMap.set(VFG.Util.getUuid(),entity);
	return entity;
}

/**
 * 水平面积测量
 */
VFG.Map.prototype.measureArea = function() {
	let entity = new VFG.MeasureArea( this.viewer);
	this.measureLayerMap.set(VFG.Util.getUuid(),entity);
	return entity;
}

/**
 * 三角测量
 */
VFG.Map.prototype.measureTriangle = function() {
	let entity = new VFG.MeasureTriangle(this.viewer);
	this.measureLayerMap.set(VFG.Util.getUuid(),entity);
	return entity;
}


/**
 * 当前视角
 */
VFG.Map.prototype.getVisualAngle=function() {
	return VFG.Util.getVisualAngle(this.viewer)
};

/**
 * 预案漫游
 */
VFG.Map.prototype.planRoam=function(options) {
	return new VFG.PlanRoam(this.viewer,options)
};

/**
 * 飞行
 */
VFG.Map.prototype.flyTo=function(option) {
	VFG.Util.flyTo(this.viewer,option);
};

/**
 * 屏幕坐标转世界坐标
 */
VFG.Map.prototype.getScreenToC3=function(position, noPickEntity) {
	return VFG.Util.getScreenToC3(this.viewer,position, noPickEntity);
}

/**
 * 世间坐标转经纬度
 */
VFG.Map.prototype.getLnLaFormC3 = function(cartesian3) {
	return VFG.Util.getLnLaFormC3(this.viewer,cartesian3);
}

VFG.Map.prototype.openWebSocket = function(ws) {
	 if ("WebSocket" in window){
	      var ws = new WebSocket(ws);
	      ws.onopen = function(){
	         ws.send("发送数据");
	         console.log("连接已关闭...");
	      };
	      ws.onmessage = function (evt) { 
	      };
	      ws.onclose = function(){ 
	         console.log("连接已关闭...");
	      };
	 }
}

VFG.Map.prototype.createEvent = function() {
	return new VFG.Event(this.viewer);
}

/**
 * 监听
 * {
 *  position:{},
 *  callback:function(Listener)
 * }
 */
VFG.Map.prototype.createListener = function(option) {
	return new VFG.Listener(this.viewer,option);
}


/**
 * 拾取对象
 */
VFG.Map.prototype.pick = function(position) {
	let obj=VFG.Util.pick(this.viewer,position);
	if(Cesium.defined(obj)){
		if(obj.id instanceof Cesium.Entity){
			return this.getById(obj.id.id);
		}else{
			return this.getById(obj.id);
		}
	}
}

VFG.Map.prototype.flyToChina = function() {
	var rectangle = Cesium.Rectangle.fromDegrees(90, -20, 110, 90);
	var center = Cesium.Rectangle.center(rectangle);//获取视角范围中心点(得到的结果为弧度Cartographic)
	var adre = Cesium.Cartographic.toCartesian(center);//把弧度转换为x,y,z（世界坐标也就是Cartographic3）
	var ellipsoid = this.viewer.scene.globe.ellipsoid;
	var cartographic = ellipsoid.cartesianToCartographic(adre);
	var lat = Cesium.Math.toDegrees(cartographic.latitude);//纬度
	var lng = Cesium.Math.toDegrees(cartographic.longitude);//经度
	this.viewer.camera.flyTo({//定位到范围中心点
	  destination: rectangle,
	  orientation: {
	     heading: Cesium.Math.toRadians(180),//1
	     pitch: Cesium.Math.toRadians(-90),
	     roll: 0
	  }
	});
}

VFG.Map.prototype.flyToPoisition = function(position) {
	if(position){
		this.viewer.camera.flyTo({//定位到范围中心点
			  destination: Cesium.Cartesian3.fromDegrees(position.x*1, position.y*1,(position.z*1)+500),
			  orientation: {
			     heading: Cesium.Math.toRadians(180),//1
			     pitch: Cesium.Math.toRadians(-90),
			     roll: 0
			  }
			});
	}
}

VFG.Map.prototype.flyToThing = function(thing) {
	if(thing){
		if(thing instanceof VFG.PModel){
			this.flyToPoisition({
				x:thing.position.x,
				y:thing.position.y,
				z:thing.getRadius(),
			});
		}
		else if(thing instanceof VFG.VModel){
			this.flyToPoisition({
				x:thing.position.x,
				y:thing.position.y,
				z:thing.getRadius(),
			});
		}else{
			this.flyToPoisition(thing.position);
		}
	}
}

VFG.Map.prototype.createPopup = function(options) {
	return new VFG.Popup(this.viewer, options)
}

VFG.Map.prototype.drawCircle = function(options) {
	return  new VFG.DrawCircle(this.viewer,options)
}

/**
 * 创建Tip对象
 */
VFG.Map.prototype.createTip = function() {
	return new VFG.Tip(this.viewer)
}

VFG.Map.prototype.getScreenToLnLa =function(position, noPickEntity) {
	return VFG.Util.getScreenToLnLa(this.viewer, position, noPickEntity) 
}

VFG.Map.prototype.hideGlobe=function() {
	this.viewer.scene.sun.show = true; 
	this.viewer.scene.moon.show = false;
	this.viewer.scene.skyBox.show = true;//关闭天空盒，否则会显示天空颜色
	this.viewer.scene.globe.show = false; //不显示地球，这条和地球透明度选一个就可以
	this.viewer.scene.globe.baseColor = new Cesium.Color(0, 0, 0, 0);
	this.viewer.scene.backgroundcolor = new Cesium.Color(0, 0, 0, 0)
};

VFG.Map.prototype.addEventListener=function(type,fun) {
	if('cameraChanged'==type){
		if(Cesium.defined(this.cameraChangedEvent)){
			this.removeEventListener(type);
		}
		this.cameraChangedEvent=fun;
		this.viewer.scene.camera.changed.addEventListener(this.cameraChangedEvent, this);
		return;
	}
	
	if('cameraMoveEnd'==type){
		if(Cesium.defined(this.cameraMoveEnd)){
			this.removeEventListener(type);
		}
		this.cameraMoveEnd=fun;
		this.viewer.scene.camera.moveEnd.addEventListener(this.cameraMoveEnd, this);
		return;
	}
	
	if('mouseMove'==type){
		this.mouseMoveFun=fun;
		return;
	}
};

VFG.Map.prototype.removeEventListener=function(type) {
	if('cameraChanged'==type){
		this.viewer.scene.camera.changed.removeEventListener(this.cameraChangedEvent, this);
		this.cameraChangedEvent=null;
		return
	}
	
	if('cameraMoveEnd'==type){
		if(Cesium.defined(this.cameraMoveEnd)){
			this.removeEventListener(type);
		}
		this.viewer.scene.camera.moveEnd.removeEventListener(this.cameraMoveEnd, this);
		this.cameraMoveEnd=null;
		return;
	}
	if('mouseMove'==type){
		this.mouseMoveFun=null;
		return;
	}
	
};

VFG.Map.prototype.getCurrentCameraInfo=function(movement) {
	let camera={};
    camera.height = this.viewer.camera.positionCartographic.height.toFixed(1);
    camera.heading = Cesium.Math.toDegrees(this.viewer.camera.heading).toFixed(0);
    camera.pitch = Cesium.Math.toDegrees(this.viewer.camera.pitch).toFixed(0);
    camera.pitch = Cesium.Math.toDegrees(this.viewer.camera.pitch).toFixed(0);
	return camera
};

/**
 * 获取鼠标位置经纬度
 */
VFG.Map.prototype.getCurrentMousePosition=function(position) {
	let locationData={};
	var cartesian = VFG.Util.getScreenToC3(this.viewer, position);
	if (!cartesian) return;
	var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
	locationData.z = (cartographic.height / this.viewer.scene.terrainExaggeration).toFixed(1);
	locationData.x = Cesium.Math.toDegrees(cartographic.longitude);
	locationData.y = Cesium.Math.toDegrees(cartographic.latitude);
	return locationData
};


//提取地球视域边界
VFG.Map.prototype.getExtent=function(opts) {
    opts = opts || {};

    // 范围对象
    var extent = {
        xmin: 0,
        xmax: 0,
        ymin: 0,
        ymax: 0
    };

    // var rectangle = viewer.camera.computeViewRectangle(); //不支持二维模式
    // if (rectangle == null) return null; 
    // var extent = formatRectangle(rectangle);  // 范围对象

    //默认值：中国区域
    extent = {
        xmin: 70,
        xmax: 140,
        ymin: 0,
        ymax: 55,
        height: 0
    };

    // 得到当前三维场景
    var viewer = this.viewer;
    var scene = viewer.scene;

    // 得到当前三维场景的椭球体
    var ellipsoid = scene.globe.ellipsoid;
    var canvas = scene.canvas;

    // canvas左上角
    var car3_lt = viewer.camera.pickEllipsoid(new Cesium.Cartesian2(0, 0), ellipsoid);
    if (car3_lt) {
        // 在椭球体上
        var carto_lt = ellipsoid.cartesianToCartographic(car3_lt);
        extent.xmin = Cesium.Math.toDegrees(carto_lt.longitude);
        extent.ymax = Cesium.Math.toDegrees(carto_lt.latitude);
        extent.height = Math.max(extent.height, carto_lt.height);
    } else {
        // 不在椭球体上 
        var xMax = canvas.width / 2;
        var yMax = canvas.height / 2;

        var car3_lt2;
        // 这里每次10像素递加，一是10像素相差不大，二是为了提高程序运行效率
        for (var yIdx = 0; yIdx <= yMax; yIdx += 10) {
            var xIdx = yIdx <= xMax ? yIdx : xMax;
            car3_lt2 = viewer.camera.pickEllipsoid(new Cesium.Cartesian2(xIdx, yIdx), ellipsoid);
            if (car3_lt2) break;
        }
        if (car3_lt2) {
            var carto_lt = ellipsoid.cartesianToCartographic(car3_lt2);
            extent.xmin = Cesium.Math.toDegrees(carto_lt.longitude);
            extent.ymax = Cesium.Math.toDegrees(carto_lt.latitude);
            extent.height = Math.max(extent.height, carto_lt.height);
        }
    }

    // canvas右下角
    var car3_rb = viewer.camera.pickEllipsoid(new Cesium.Cartesian2(canvas.width, canvas.height), ellipsoid);
    if (car3_rb) {
        // 在椭球体上
        var carto_rb = ellipsoid.cartesianToCartographic(car3_rb);
        extent.xmax = Cesium.Math.toDegrees(carto_rb.longitude);
        extent.ymin = Cesium.Math.toDegrees(carto_rb.latitude);
        extent.height = Math.max(extent.height, carto_rb.height);
    } else {
        // 不在椭球体上
        var xMax = canvas.width / 2;
        var yMax = canvas.height / 2;

        var car3_rb2;
        // 这里每次10像素递减，一是10像素相差不大，二是为了提高程序运行效率
        for (var yIdx = canvas.height; yIdx >= yMax; yIdx -= 10) {
            var xIdx = yIdx >= xMax ? yIdx : xMax;
            car3_rb2 = viewer.camera.pickEllipsoid(new Cesium.Cartesian2(xIdx, yIdx), ellipsoid);
            if (car3_rb2) break;
        }
        if (car3_rb2) {
            var carto_rb = ellipsoid.cartesianToCartographic(car3_rb2);
            extent.xmax = Cesium.Math.toDegrees(carto_rb.longitude);
            extent.ymin = Cesium.Math.toDegrees(carto_rb.latitude);
            extent.height = Math.max(extent.height, carto_rb.height);
        }
    }

    
    //交换
    if (extent.xmax < extent.xmin) {
        var temp = extent.xmax;
        extent.xmax = extent.xmin;
        extent.xmin = temp;
    }
    if (extent.ymax < extent.ymin) {
        var temp = extent.ymax;
        extent.ymax = extent.ymin;
        extent.ymin = temp;
    }

    //缩放
    if (opts.scale) {
        var old_xmin = extent.xmin;
        var old_xmax = extent.xmax;
        var old_ymin = extent.ymin;
        var old_ymax = extent.ymax;

        //限定最大倍数
        if (opts.scale > 3) opts.scale = 3;
        if (opts.scale < -3) opts.scale = -3;

        var stepx = (extent.xmax - extent.xmin) * opts.scale;
        extent.xmin -= stepx;
        extent.xmax += stepx;
        var stepy = (extent.ymax - extent.ymin) * opts.scale;
        extent.ymin -= stepy;
        extent.ymax += stepy;

        //如果超出地球范围，还原放大的值
        if (extent.xmin < -180 || extent.xmax > 180 || extent.ymin < -90 || extent.ymax > 90) {
            extent.xmin = old_xmin;
            extent.xmax = old_xmax;
            extent.ymin = old_ymin;
            extent.ymax = old_ymax;
        }
    }

    return extent;
}

//计算地图缩放等级
VFG.Map.prototype.getZoomLevel=function() {
	 let h =this.viewer.camera.positionCartographic.height.toFixed(1)
    if (h <= 100) { //0.01
        return 19;
    } else if (h <= 300) { //0.02
        return 18;
    } else if (h <= 660) { //0.05
        return 17;
    } else if (h <= 1300) { //0.1
        return 16;
    } else if (h <= 2600) { //0.2
        return 15;
    } else if (h <= 6400) { //0.5
        return 14;
    } else if (h <= 13200) { //1
        return 13;
    } else if (h <= 26000) { //2
        return 12;
    } else if (h <= 67985) { //5
        return 11;
    } else if (h <= 139780) { //10
        return 10;
    } else if (h <= 250600) { //20
        return 9;
    } else if (h <= 380000) { //30
        return 8;
    } else if (h <= 640000) { //50
        return 7;
    } else if (h <= 1280000) { //100
        return 6;
    } else if (h <= 2600000) { //200
        return 5;
    } else if (h <= 6100000) { //500
        return 4;
    } else if (h <= 11900000) { //1000
        return 3;
    } else {
        return 2;
    }
}

VFG.Map.prototype.wgs84ToWindowCoordinates=function(position){
	let cartesian3=Cesium.Cartesian3.fromDegrees(position.x*1, position.y*1, position.z*1);
	if(cartesian3){
		return  Cesium.SceneTransforms.wgs84ToWindowCoordinates(this.viewer.scene, cartesian3)
	}
	return null;
}




/**
 * 销毁对象
 */
VFG.Map.prototype.destroy = function() {
  if (this.viewer) {
    this.viewer.destroy();
    this.viewer = null;
  }
}
;
///<jscompress sourcefile="CesiumGeometry.js" />
(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory();
	else if(typeof define === 'function' && define.amd)
		define([], factory);
	else if(typeof exports === 'object')
		exports["CesiumGeometry"] = factory();
	else
		root["CesiumGeometry"] = factory();
})(typeof self !== 'undefined' ? self : this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 4);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.RectangularSensorPrimitive = undefined;

var _RectangularSensorVS = __webpack_require__(6);

var _RectangularSensorVS2 = _interopRequireDefault(_RectangularSensorVS);

var _RectangularSensorFS = __webpack_require__(7);

var _RectangularSensorFS2 = _interopRequireDefault(_RectangularSensorFS);

var _RectangularSensor = __webpack_require__(8);

var _RectangularSensor2 = _interopRequireDefault(_RectangularSensor);

var _RectangularSensorScanPlaneFS = __webpack_require__(9);

var _RectangularSensorScanPlaneFS2 = _interopRequireDefault(_RectangularSensorScanPlaneFS);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var BoundingSphere = Cesium.BoundingSphere;
var Cartesian3 = Cesium.Cartesian3;
var Color = Cesium.Color;
var combine = Cesium.combine;
var ComponentDatatype = Cesium.ComponentDatatype;
var defaultValue = Cesium.defaultValue;
var defined = Cesium.defined;
var defineProperties = Object.defineProperties;
var destroyObject = Cesium.destroyObject;
var DeveloperError = Cesium.DeveloperError;
var Matrix4 = Cesium.Matrix4;
var PrimitiveType = Cesium.PrimitiveType;
var Buffer = Cesium.Buffer;
var BufferUsage = Cesium.BufferUsage;
var DrawCommand = Cesium.DrawCommand;
var Pass = Cesium.Pass;
var RenderState = Cesium.RenderState;
var ShaderProgram = Cesium.ShaderProgram;
var ShaderSource = Cesium.ShaderSource;
var VertexArray = Cesium.VertexArray;
var BlendingState = Cesium.BlendingState;
var CullFace = Cesium.CullFace;
var Material = Cesium.Material;
var SceneMode = Cesium.SceneMode;
var VertexFormat = Cesium.VertexFormat;
var CesiumMath = Cesium.Math;
var Matrix3 = Cesium.Matrix3;
var Matrix4 = Cesium.Matrix4;
var JulianDate = Cesium.JulianDate;

var BoxGeometry = Cesium.BoxGeometry;
var EllipsoidGeometry = Cesium.EllipsoidGeometry;

var sin = Math.sin;
var cos = Math.cos;
var tan = Math.tan;
var atan = Math.atan;
var asin = Math.asin;

var attributeLocations = {
    position: 0,
    normal: 1
};

function RectangularSensorPrimitive(options) {
    var self = this;

    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    /**
     * 是否显示
     */
    this.show = defaultValue(options.show, true);

    /**
     * 切分程度
     */
    this.slice = defaultValue(options.slice, 32);

    /**
     * 传感器的模型矩阵
     */
    this.modelMatrix = Matrix4.clone(options.modelMatrix, new Matrix4());
    this._modelMatrix = new Matrix4();
    this._computedModelMatrix = new Matrix4();
    this._computedScanPlaneModelMatrix = new Matrix4();

    /**
     * 传感器的半径
     */
    this.radius = defaultValue(options.radius, Number.POSITIVE_INFINITY);
    this._radius = undefined;

    /**
     * 传感器水平半角
     */
    this.xHalfAngle = defaultValue(options.xHalfAngle, 0);
    this._xHalfAngle = undefined;

    /**
     * 传感器垂直半角
     */
    this.yHalfAngle = defaultValue(options.yHalfAngle, 0);
    this._yHalfAngle = undefined;

    /**
     * 线的颜色
     */
    this.lineColor = defaultValue(options.lineColor, Color.WHITE);

    /**
     * 是否显示扇面的线
     */
    this.showSectorLines = defaultValue(options.showSectorLines, true);

    /**
     * 是否显示扇面和圆顶面连接的线
     */
    this.showSectorSegmentLines = defaultValue(options.showSectorSegmentLines, true);

    /**
     * 是否显示侧面
     */
    this.showLateralSurfaces = defaultValue(options.showLateralSurfaces, true);

    /**
     * 目前用的统一材质
     * @type {Material}
     */
    this.material = defined(options.material) ? options.material : Material.fromType(Material.ColorType);
    this._material = undefined;
    this._translucent = undefined;

    /**
     * 侧面材质
     * @type {Material}
     */
    this.lateralSurfaceMaterial = defined(options.lateralSurfaceMaterial) ? options.lateralSurfaceMaterial : Material.fromType(Material.ColorType);
    this._lateralSurfaceMaterial = undefined;
    this._lateralSurfaceTranslucent = undefined;

    /**
     * 是否显示圆顶表面
     */
    this.showDomeSurfaces = defaultValue(options.showDomeSurfaces, true);

    /**
     * 圆顶表面材质
     * @type {Material}
     */
    this.domeSurfaceMaterial = defined(options.domeSurfaceMaterial) ? options.domeSurfaceMaterial : Material.fromType(Material.ColorType);
    this._domeSurfaceMaterial = undefined;

    /**
     * 是否显示圆顶面线
     */
    this.showDomeLines = defaultValue(options.showDomeLines, true);

    /**
     * 是否显示与地球相交的线
     */
    this.showIntersection = defaultValue(options.showIntersection, true);

    /**
     * 与地球相交的线的颜色
     */
    this.intersectionColor = defaultValue(options.intersectionColor, Color.WHITE);

    /**
     * 与地球相交的线的宽度（像素）
     */
    this.intersectionWidth = defaultValue(options.intersectionWidth, 5.0);

    /**
     * 是否穿过地球
     */
    this.showThroughEllipsoid = defaultValue(options.showThroughEllipsoid, false);
    this._showThroughEllipsoid = undefined;

    /**
     * 是否显示扫描面
     */
    this.showScanPlane = defaultValue(options.showScanPlane, true);

    /**
     * 扫描面颜色
     */
    this.scanPlaneColor = defaultValue(options.scanPlaneColor, Color.WHITE);

    /**
     * 扫描面模式 垂直vertical/水平horizontal
     */
    this.scanPlaneMode = defaultValue(options.scanPlaneMode, 'horizontal');

    /**
     * 扫描速率
     */
    this.scanPlaneRate = defaultValue(options.scanPlaneRate, 10);

    this._scanePlaneXHalfAngle = 0;
    this._scanePlaneYHalfAngle = 0;

    //时间计算的起点
    this._time = JulianDate.now();

    this._boundingSphere = new BoundingSphere();
    this._boundingSphereWC = new BoundingSphere();

    //扇面 sector
    this._sectorFrontCommand = new DrawCommand({
        owner: this,
        primitiveType: PrimitiveType.TRIANGLES,
        boundingVolume: this._boundingSphereWC
    });
    this._sectorBackCommand = new DrawCommand({
        owner: this,
        primitiveType: PrimitiveType.TRIANGLES,
        boundingVolume: this._boundingSphereWC
    });
    this._sectorVA = undefined;

    //扇面边线 sectorLine
    this._sectorLineCommand = new DrawCommand({
        owner: this,
        primitiveType: PrimitiveType.LINES,
        boundingVolume: this._boundingSphereWC
    });
    this._sectorLineVA = undefined;

    //扇面分割线 sectorSegmentLine
    this._sectorSegmentLineCommand = new DrawCommand({
        owner: this,
        primitiveType: PrimitiveType.LINES,
        boundingVolume: this._boundingSphereWC
    });
    this._sectorSegmentLineVA = undefined;

    //弧面 dome
    this._domeFrontCommand = new DrawCommand({
        owner: this,
        primitiveType: PrimitiveType.TRIANGLES,
        boundingVolume: this._boundingSphereWC
    });
    this._domeBackCommand = new DrawCommand({
        owner: this,
        primitiveType: PrimitiveType.TRIANGLES,
        boundingVolume: this._boundingSphereWC
    });
    this._domeVA = undefined;

    //弧面线 domeLine
    this._domeLineCommand = new DrawCommand({
        owner: this,
        primitiveType: PrimitiveType.LINES,
        boundingVolume: this._boundingSphereWC
    });
    this._domeLineVA = undefined;

    //扫描面 scanPlane/scanRadial
    this._scanPlaneFrontCommand = new DrawCommand({
        owner: this,
        primitiveType: PrimitiveType.TRIANGLES,
        boundingVolume: this._boundingSphereWC
    });
    this._scanPlaneBackCommand = new DrawCommand({
        owner: this,
        primitiveType: PrimitiveType.TRIANGLES,
        boundingVolume: this._boundingSphereWC
    });

    this._scanRadialCommand = undefined;

    this._colorCommands = [];

    this._frontFaceRS = undefined;
    this._backFaceRS = undefined;
    this._sp = undefined;

    this._uniforms = {
        u_type: function u_type() {
            return 0; //面
        },
        u_xHalfAngle: function u_xHalfAngle() {
            return self.xHalfAngle;
        },
        u_yHalfAngle: function u_yHalfAngle() {
            return self.yHalfAngle;
        },
        u_radius: function u_radius() {
            return self.radius;
        },
        u_showThroughEllipsoid: function u_showThroughEllipsoid() {
            return self.showThroughEllipsoid;
        },
        u_showIntersection: function u_showIntersection() {
            return self.showIntersection;
        },
        u_intersectionColor: function u_intersectionColor() {
            return self.intersectionColor;
        },
        u_intersectionWidth: function u_intersectionWidth() {
            return self.intersectionWidth;
        },
        u_normalDirection: function u_normalDirection() {
            return 1.0;
        },
        u_lineColor: function u_lineColor() {
            return self.lineColor;
        }
    };

    this._scanUniforms = {
        u_xHalfAngle: function u_xHalfAngle() {
            return self._scanePlaneXHalfAngle;
        },
        u_yHalfAngle: function u_yHalfAngle() {
            return self._scanePlaneYHalfAngle;
        },
        u_radius: function u_radius() {
            return self.radius;
        },
        u_color: function u_color() {
            return self.scanPlaneColor;
        },
        u_showThroughEllipsoid: function u_showThroughEllipsoid() {
            return self.showThroughEllipsoid;
        },
        u_showIntersection: function u_showIntersection() {
            return self.showIntersection;
        },
        u_intersectionColor: function u_intersectionColor() {
            return self.intersectionColor;
        },
        u_intersectionWidth: function u_intersectionWidth() {
            return self.intersectionWidth;
        },
        u_normalDirection: function u_normalDirection() {
            return 1.0;
        },
        u_lineColor: function u_lineColor() {
            return self.lineColor;
        }
    };
}
RectangularSensorPrimitive.prototype.isDestroyed = function(){ return false}
RectangularSensorPrimitive.prototype.destroy = function(){ }
RectangularSensorPrimitive.prototype.update = function (frameState) {
    var mode = frameState.mode;
    if (!this.show || mode !== SceneMode.SCENE3D) {
        return;
    }
    var createVS = false;
    var createRS = false;
    var createSP = false;

    var xHalfAngle = this.xHalfAngle;
    var yHalfAngle = this.yHalfAngle;

    if (xHalfAngle < 0.0 || yHalfAngle < 0.0) {
        throw new DeveloperError('halfAngle must be greater than or equal to zero.');
    }
    if (xHalfAngle == 0.0 || yHalfAngle == 0.0) {
        return;
    }
    if (this._xHalfAngle !== xHalfAngle || this._yHalfAngle !== yHalfAngle) {
        this._xHalfAngle = xHalfAngle;
        this._yHalfAngle = yHalfAngle;
        createVS = true;
    }

    var radius = this.radius;
    if (radius < 0.0) {
        throw new DeveloperError('this.radius must be greater than or equal to zero.');
    }
    var radiusChanged = false;
    if (this._radius !== radius) {
        radiusChanged = true;
        this._radius = radius;
        this._boundingSphere = new BoundingSphere(Cartesian3.ZERO, this.radius);
    }

    var modelMatrixChanged = !Matrix4.equals(this.modelMatrix, this._modelMatrix);
    if (modelMatrixChanged || radiusChanged) {
        Matrix4.clone(this.modelMatrix, this._modelMatrix);
        Matrix4.multiplyByUniformScale(this.modelMatrix, this.radius, this._computedModelMatrix);
        BoundingSphere.transform(this._boundingSphere, this.modelMatrix, this._boundingSphereWC);
    }

    var showThroughEllipsoid = this.showThroughEllipsoid;
    if (this._showThroughEllipsoid !== this.showThroughEllipsoid) {
        this._showThroughEllipsoid = showThroughEllipsoid;
        createRS = true;
    }

    var material = this.material;
    if (this._material !== material) {
        this._material = material;
        createRS = true;
        createSP = true;
    }
    var translucent = material.isTranslucent();
    if (this._translucent !== translucent) {
        this._translucent = translucent;
        createRS = true;
    }

    if (this.showScanPlane) {
        var time = frameState.time;
        var timeDiff = JulianDate.secondsDifference(time, this._time);
        if (timeDiff < 0) {
            this._time = JulianDate.clone(time, this._time);
        }
        var percentage = Math.max(timeDiff % this.scanPlaneRate / this.scanPlaneRate, 0);
        var angle;

        if (this.scanPlaneMode == 'horizontal') {
            angle = 2 * yHalfAngle * percentage - yHalfAngle;
            var cosYHalfAngle = cos(angle);
            var tanXHalfAngle = tan(xHalfAngle);

            var maxX = atan(cosYHalfAngle * tanXHalfAngle);
            this._scanePlaneXHalfAngle = maxX;
            this._scanePlaneYHalfAngle = angle;
            Cesium.Matrix3.fromRotationX(this._scanePlaneYHalfAngle, matrix3Scratch);
        } else {
            angle = 2 * xHalfAngle * percentage - xHalfAngle;
            var tanYHalfAngle = tan(yHalfAngle);
            var cosXHalfAngle = cos(angle);

            var maxY = atan(cosXHalfAngle * tanYHalfAngle);
            this._scanePlaneXHalfAngle = angle;
            this._scanePlaneYHalfAngle = maxY;
            Cesium.Matrix3.fromRotationY(this._scanePlaneXHalfAngle, matrix3Scratch);
        }

        Cesium.Matrix4.multiplyByMatrix3(this.modelMatrix, matrix3Scratch, this._computedScanPlaneModelMatrix);
        Matrix4.multiplyByUniformScale(this._computedScanPlaneModelMatrix, this.radius, this._computedScanPlaneModelMatrix);
    }

    if (createVS) {
        createVertexArray(this, frameState);
    }
    if (createRS) {
        createRenderState(this, showThroughEllipsoid, translucent);
    }
    if (createSP) {
        createShaderProgram(this, frameState, material);
    }
    if (createRS || createSP) {
        createCommands(this, translucent);
    }

    var commandList = frameState.commandList;
    var passes = frameState.passes;
    var colorCommands = this._colorCommands;
    if (passes.render) {
        for (var i = 0, len = colorCommands.length; i < len; i++) {
            var colorCommand = colorCommands[i];
            commandList.push(colorCommand);
        }
    }
};

var matrix3Scratch = new Matrix3();
var nScratch = new Cartesian3();

//region -- VertexArray --

/**
 * 计算zoy面和zoy面单位扇形位置
 * @param primitive
 * @returns {{zoy: Array, zox: Array}}
 */
function computeUnitPosiiton(primitive, xHalfAngle, yHalfAngle) {
    var slice = primitive.slice;

    //以中心为角度
    var cosYHalfAngle = cos(yHalfAngle);
    var tanYHalfAngle = tan(yHalfAngle);
    var cosXHalfAngle = cos(xHalfAngle);
    var tanXHalfAngle = tan(xHalfAngle);

    var maxY = atan(cosXHalfAngle * tanYHalfAngle);
    var maxX = atan(cosYHalfAngle * tanXHalfAngle);

    //ZOY面单位圆
    var zoy = [];
    for (var i = 0; i < slice; i++) {
        var phi = 2 * maxY * i / (slice - 1) - maxY;
        zoy.push(new Cartesian3(0, sin(phi), cos(phi)));
    }
    //zox面单位圆
    var zox = [];
    for (var i = 0; i < slice; i++) {
        var phi = 2 * maxX * i / (slice - 1) - maxX;
        zox.push(new Cartesian3(sin(phi), 0, cos(phi)));
    }

    return {
        zoy: zoy,
        zox: zox
    };
}

/**
 * 计算扇面的位置
 * @param unitPosition
 * @returns {Array}
 */
function computeSectorPositions(primitive, unitPosition) {
    var xHalfAngle = primitive.xHalfAngle,
        yHalfAngle = primitive.yHalfAngle,
        zoy = unitPosition.zoy,
        zox = unitPosition.zox;
    var positions = [];

    //zoy面沿y轴逆时针转xHalfAngle
    var matrix3 = Matrix3.fromRotationY(xHalfAngle, matrix3Scratch);
    positions.push(zoy.map(function (p) {
        return Matrix3.multiplyByVector(matrix3, p, new Cesium.Cartesian3());
    }));
    //zox面沿x轴顺时针转yHalfAngle
    var matrix3 = Matrix3.fromRotationX(-yHalfAngle, matrix3Scratch);
    positions.push(zox.map(function (p) {
        return Matrix3.multiplyByVector(matrix3, p, new Cesium.Cartesian3());
    }).reverse());
    //zoy面沿y轴顺时针转xHalfAngle
    var matrix3 = Matrix3.fromRotationY(-xHalfAngle, matrix3Scratch);
    positions.push(zoy.map(function (p) {
        return Matrix3.multiplyByVector(matrix3, p, new Cesium.Cartesian3());
    }).reverse());
    //zox面沿x轴逆时针转yHalfAngle
    var matrix3 = Matrix3.fromRotationX(yHalfAngle, matrix3Scratch);
    positions.push(zox.map(function (p) {
        return Matrix3.multiplyByVector(matrix3, p, new Cesium.Cartesian3());
    }));
    return positions;
}

/**
 * 创建扇面顶点
 * @param context
 * @param positions
 * @returns {*}
 */
function createSectorVertexArray(context, positions) {
    var planeLength = Array.prototype.concat.apply([], positions).length - positions.length;
    var vertices = new Float32Array(2 * 3 * 3 * planeLength);

    var k = 0;
    for (var i = 0, len = positions.length; i < len; i++) {
        var planePositions = positions[i];
        var n = Cartesian3.normalize(Cartesian3.cross(planePositions[0], planePositions[planePositions.length - 1], nScratch), nScratch);
        for (var j = 0, planeLength = planePositions.length - 1; j < planeLength; j++) {
            vertices[k++] = 0.0;
            vertices[k++] = 0.0;
            vertices[k++] = 0.0;
            vertices[k++] = -n.x;
            vertices[k++] = -n.y;
            vertices[k++] = -n.z;

            vertices[k++] = planePositions[j].x;
            vertices[k++] = planePositions[j].y;
            vertices[k++] = planePositions[j].z;
            vertices[k++] = -n.x;
            vertices[k++] = -n.y;
            vertices[k++] = -n.z;

            vertices[k++] = planePositions[j + 1].x;
            vertices[k++] = planePositions[j + 1].y;
            vertices[k++] = planePositions[j + 1].z;
            vertices[k++] = -n.x;
            vertices[k++] = -n.y;
            vertices[k++] = -n.z;
        }
    }

    var vertexBuffer = Buffer.createVertexBuffer({
        context: context,
        typedArray: vertices,
        usage: BufferUsage.STATIC_DRAW
    });

    var stride = 2 * 3 * Float32Array.BYTES_PER_ELEMENT;

    var attributes = [{
        index: attributeLocations.position,
        vertexBuffer: vertexBuffer,
        componentsPerAttribute: 3,
        componentDatatype: ComponentDatatype.FLOAT,
        offsetInBytes: 0,
        strideInBytes: stride
    }, {
        index: attributeLocations.normal,
        vertexBuffer: vertexBuffer,
        componentsPerAttribute: 3,
        componentDatatype: ComponentDatatype.FLOAT,
        offsetInBytes: 3 * Float32Array.BYTES_PER_ELEMENT,
        strideInBytes: stride
    }];

    return new VertexArray({
        context: context,
        attributes: attributes
    });
}

/**
 * 创建扇面边线顶点
 * @param context
 * @param positions
 * @returns {*}
 */
function createSectorLineVertexArray(context, positions) {
    var planeLength = positions.length;
    var vertices = new Float32Array(3 * 3 * planeLength);

    var k = 0;
    for (var i = 0, len = positions.length; i < len; i++) {
        var planePositions = positions[i];
        vertices[k++] = 0.0;
        vertices[k++] = 0.0;
        vertices[k++] = 0.0;

        vertices[k++] = planePositions[0].x;
        vertices[k++] = planePositions[0].y;
        vertices[k++] = planePositions[0].z;
    }

    var vertexBuffer = Buffer.createVertexBuffer({
        context: context,
        typedArray: vertices,
        usage: BufferUsage.STATIC_DRAW
    });

    var stride = 3 * Float32Array.BYTES_PER_ELEMENT;

    var attributes = [{
        index: attributeLocations.position,
        vertexBuffer: vertexBuffer,
        componentsPerAttribute: 3,
        componentDatatype: ComponentDatatype.FLOAT,
        offsetInBytes: 0,
        strideInBytes: stride
    }];

    return new VertexArray({
        context: context,
        attributes: attributes
    });
}

/**
 * 创建扇面圆顶面连接线顶点
 * @param context
 * @param positions
 * @returns {*}
 */
function createSectorSegmentLineVertexArray(context, positions) {
    var planeLength = Array.prototype.concat.apply([], positions).length - positions.length;
    var vertices = new Float32Array(3 * 3 * planeLength);

    var k = 0;
    for (var i = 0, len = positions.length; i < len; i++) {
        var planePositions = positions[i];

        for (var j = 0, planeLength = planePositions.length - 1; j < planeLength; j++) {
            vertices[k++] = planePositions[j].x;
            vertices[k++] = planePositions[j].y;
            vertices[k++] = planePositions[j].z;

            vertices[k++] = planePositions[j + 1].x;
            vertices[k++] = planePositions[j + 1].y;
            vertices[k++] = planePositions[j + 1].z;
        }
    }

    var vertexBuffer = Buffer.createVertexBuffer({
        context: context,
        typedArray: vertices,
        usage: BufferUsage.STATIC_DRAW
    });

    var stride = 3 * Float32Array.BYTES_PER_ELEMENT;

    var attributes = [{
        index: attributeLocations.position,
        vertexBuffer: vertexBuffer,
        componentsPerAttribute: 3,
        componentDatatype: ComponentDatatype.FLOAT,
        offsetInBytes: 0,
        strideInBytes: stride
    }];

    return new VertexArray({
        context: context,
        attributes: attributes
    });
}

/**
 * 创建圆顶面顶点
 * @param context
 */
function createDomeVertexArray(context) {
    var geometry = Cesium.EllipsoidGeometry.createGeometry(new Cesium.EllipsoidGeometry({
        vertexFormat: VertexFormat.POSITION_ONLY,
        stackPartitions: 32,
        slicePartitions: 32
    }));

    var vertexArray = VertexArray.fromGeometry({
        context: context,
        geometry: geometry,
        attributeLocations: attributeLocations,
        bufferUsage: BufferUsage.STATIC_DRAW,
        interleave: false
    });
    return vertexArray;
}

/**
 * 创建圆顶面连线顶点
 * @param context
 */
function createDomeLineVertexArray(context) {
    var geometry = Cesium.EllipsoidOutlineGeometry.createGeometry(new Cesium.EllipsoidOutlineGeometry({
        vertexFormat: VertexFormat.POSITION_ONLY,
        stackPartitions: 32,
        slicePartitions: 32
    }));

    var vertexArray = VertexArray.fromGeometry({
        context: context,
        geometry: geometry,
        attributeLocations: attributeLocations,
        bufferUsage: BufferUsage.STATIC_DRAW,
        interleave: false
    });
    return vertexArray;
}

/**
 * 创建扫描面顶点
 * @param context
 * @param positions
 * @returns {*}
 */
function createScanPlaneVertexArray(context, positions) {
    var planeLength = positions.length - 1;
    var vertices = new Float32Array(3 * 3 * planeLength);

    var k = 0;
    for (var i = 0; i < planeLength; i++) {
        vertices[k++] = 0.0;
        vertices[k++] = 0.0;
        vertices[k++] = 0.0;

        vertices[k++] = positions[i].x;
        vertices[k++] = positions[i].y;
        vertices[k++] = positions[i].z;

        vertices[k++] = positions[i + 1].x;
        vertices[k++] = positions[i + 1].y;
        vertices[k++] = positions[i + 1].z;
    }

    var vertexBuffer = Buffer.createVertexBuffer({
        context: context,
        typedArray: vertices,
        usage: BufferUsage.STATIC_DRAW
    });

    var stride = 3 * Float32Array.BYTES_PER_ELEMENT;

    var attributes = [{
        index: attributeLocations.position,
        vertexBuffer: vertexBuffer,
        componentsPerAttribute: 3,
        componentDatatype: ComponentDatatype.FLOAT,
        offsetInBytes: 0,
        strideInBytes: stride
    }];

    return new VertexArray({
        context: context,
        attributes: attributes
    });
}

function createVertexArray(primitive, frameState) {
    var context = frameState.context;

    var unitSectorPositions = computeUnitPosiiton(primitive, primitive.xHalfAngle, primitive.yHalfAngle);
    var positions = computeSectorPositions(primitive, unitSectorPositions);

    //显示扇面
    if (primitive.showLateralSurfaces) {
        primitive._sectorVA = createSectorVertexArray(context, positions);
    }

    //显示扇面线
    if (primitive.showSectorLines) {
        primitive._sectorLineVA = createSectorLineVertexArray(context, positions);
    }

    //显示扇面圆顶面的交线
    if (primitive.showSectorSegmentLines) {
        primitive._sectorSegmentLineVA = createSectorSegmentLineVertexArray(context, positions);
    }

    //显示弧面
    if (primitive.showDomeSurfaces) {
        primitive._domeVA = createDomeVertexArray(context);
    }

    //显示弧面线
    if (primitive.showDomeLines) {
        primitive._domeLineVA = createDomeLineVertexArray(context);
    }

    //显示扫描面
    if (primitive.showScanPlane) {

        if (primitive.scanPlaneMode == 'horizontal') {
            var unitScanPlanePositions = computeUnitPosiiton(primitive, CesiumMath.PI_OVER_TWO, 0);
            primitive._scanPlaneVA = createScanPlaneVertexArray(context, unitScanPlanePositions.zox);
        } else {
            var unitScanPlanePositions = computeUnitPosiiton(primitive, 0, CesiumMath.PI_OVER_TWO);
            primitive._scanPlaneVA = createScanPlaneVertexArray(context, unitScanPlanePositions.zoy);
        }
    }
}

//endregion

//region -- ShaderProgram --

function createCommonShaderProgram(primitive, frameState, material) {
    var context = frameState.context;

    var vs = _RectangularSensorVS2.default;
    var fs = new ShaderSource({
        sources: [_RectangularSensor2.default, material.shaderSource, _RectangularSensorFS2.default]
    });

    primitive._sp = ShaderProgram.replaceCache({
        context: context,
        shaderProgram: primitive._sp,
        vertexShaderSource: vs,
        fragmentShaderSource: fs,
        attributeLocations: attributeLocations
    });

    var pickFS = new ShaderSource({
        sources: [_RectangularSensor2.default, material.shaderSource, _RectangularSensorFS2.default],
        pickColorQualifier: 'uniform'
    });

    primitive._pickSP = ShaderProgram.replaceCache({
        context: context,
        shaderProgram: primitive._pickSP,
        vertexShaderSource: vs,
        fragmentShaderSource: pickFS,
        attributeLocations: attributeLocations
    });
}

function createScanPlaneShaderProgram(primitive, frameState, material) {
    var context = frameState.context;

    var vs = _RectangularSensorVS2.default;
    var fs = new ShaderSource({
        sources: [_RectangularSensor2.default, material.shaderSource, _RectangularSensorScanPlaneFS2.default]
    });

    primitive._scanePlaneSP = ShaderProgram.replaceCache({
        context: context,
        shaderProgram: primitive._scanePlaneSP,
        vertexShaderSource: vs,
        fragmentShaderSource: fs,
        attributeLocations: attributeLocations
    });
}

function createShaderProgram(primitive, frameState, material) {
    createCommonShaderProgram(primitive, frameState, material);

    if (primitive.showScanPlane) {
        createScanPlaneShaderProgram(primitive, frameState, material);
    }
}

//endregion

//region -- RenderState --

function createRenderState(primitive, showThroughEllipsoid, translucent) {
    if (translucent) {
        primitive._frontFaceRS = RenderState.fromCache({
            depthTest: {
                enabled: !showThroughEllipsoid
            },
            depthMask: false,
            blending: BlendingState.ALPHA_BLEND,
            cull: {
                enabled: true,
                face: CullFace.BACK
            }
        });

        primitive._backFaceRS = RenderState.fromCache({
            depthTest: {
                enabled: !showThroughEllipsoid
            },
            depthMask: false,
            blending: BlendingState.ALPHA_BLEND,
            cull: {
                enabled: true,
                face: CullFace.FRONT
            }
        });

        primitive._pickRS = RenderState.fromCache({
            depthTest: {
                enabled: !showThroughEllipsoid
            },
            depthMask: false,
            blending: BlendingState.ALPHA_BLEND
        });
    } else {
        primitive._frontFaceRS = RenderState.fromCache({
            depthTest: {
                enabled: !showThroughEllipsoid
            },
            depthMask: true
        });

        primitive._pickRS = RenderState.fromCache({
            depthTest: {
                enabled: true
            },
            depthMask: true
        });
    }
}

//endregion

//region -- Command --

function createCommand(primitive, frontCommand, backCommand, frontFaceRS, backFaceRS, sp, va, uniforms, modelMatrix, translucent, pass, isLine) {
    if (translucent && backCommand) {
        backCommand.vertexArray = va;
        backCommand.renderState = backFaceRS;
        backCommand.shaderProgram = sp;
        backCommand.uniformMap = combine(uniforms, primitive._material._uniforms);
        backCommand.uniformMap.u_normalDirection = function () {
            return -1.0;
        };
        backCommand.pass = pass;
        backCommand.modelMatrix = modelMatrix;
        primitive._colorCommands.push(backCommand);
    }

    frontCommand.vertexArray = va;
    frontCommand.renderState = frontFaceRS;
    frontCommand.shaderProgram = sp;
    frontCommand.uniformMap = combine(uniforms, primitive._material._uniforms);
    if (isLine) {
        frontCommand.uniformMap.u_type = function () {
            return 1;
        };
    }
    frontCommand.pass = pass;
    frontCommand.modelMatrix = modelMatrix;
    primitive._colorCommands.push(frontCommand);
}

function createCommands(primitive, translucent) {
    primitive._colorCommands.length = 0;

    var pass = translucent ? Pass.TRANSLUCENT : Pass.OPAQUE;

    //显示扇面
    if (primitive.showLateralSurfaces) {
        createCommand(primitive, primitive._sectorFrontCommand, primitive._sectorBackCommand, primitive._frontFaceRS, primitive._backFaceRS, primitive._sp, primitive._sectorVA, primitive._uniforms, primitive._computedModelMatrix, translucent, pass);
    }
    //显示扇面线
    if (primitive.showSectorLines) {
        createCommand(primitive, primitive._sectorLineCommand, undefined, primitive._frontFaceRS, primitive._backFaceRS, primitive._sp, primitive._sectorLineVA, primitive._uniforms, primitive._computedModelMatrix, translucent, pass, true);
    }
    //显示扇面交接线
    if (primitive.showSectorSegmentLines) {
        createCommand(primitive, primitive._sectorSegmentLineCommand, undefined, primitive._frontFaceRS, primitive._backFaceRS, primitive._sp, primitive._sectorSegmentLineVA, primitive._uniforms, primitive._computedModelMatrix, translucent, pass, true);
    }
    //显示弧面
    if (primitive.showDomeSurfaces) {
        createCommand(primitive, primitive._domeFrontCommand, primitive._domeBackCommand, primitive._frontFaceRS, primitive._backFaceRS, primitive._sp, primitive._domeVA, primitive._uniforms, primitive._computedModelMatrix, translucent, pass);
    }
    //显示弧面线
    if (primitive.showDomeLines) {
        createCommand(primitive, primitive._domeLineCommand, undefined, primitive._frontFaceRS, primitive._backFaceRS, primitive._sp, primitive._domeLineVA, primitive._uniforms, primitive._computedModelMatrix, translucent, pass, true);
    }
    //显示扫描面
    if (primitive.showScanPlane) {
        createCommand(primitive, primitive._scanPlaneFrontCommand, primitive._scanPlaneBackCommand, primitive._frontFaceRS, primitive._backFaceRS, primitive._scanePlaneSP, primitive._scanPlaneVA, primitive._scanUniforms, primitive._computedScanPlaneModelMatrix, translucent, pass);
    }
}

//endregion

exports.RectangularSensorPrimitive = RectangularSensorPrimitive;

/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});
var BoundingSphere = Cesium.BoundingSphere,
    Cartesian3 = Cesium.Cartesian3,
    Check = Cesium.Check,
    ComponentDatatype = Cesium.ComponentDatatype,
    defaultValue = Cesium.defaultValue,
    defined = Cesium.defined,
    Geometry = Cesium.Geometry,
    GeometryAttribute = Cesium.GeometryAttribute,
    GeometryAttributes = Cesium.GeometryAttributes,
    PrimitiveType = Cesium.PrimitiveType,
    VertexFormat = Cesium.VertexFormat,
    CesiumMath = Cesium.Math,
    GeometryPipeline = Cesium.GeometryPipeline,
    IndexDatatype = Cesium.IndexDatatype,
    Ellipsoid = Cesium.Ellipsoid;

var cos = Math.cos;
var sin = Math.sin;

function ConicArcSensorGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    var angle = options.angle;
    var radius = options.radius;

    var stackPartitions = Math.round(defaultValue(options.stackPartitions, 12));
    var slicePartitions = Math.round(defaultValue(options.slicePartitions, 64));

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number('angle', angle);
    Check.typeOf.number('radius', radius);
    //>>includeEnd('debug');

    var vertexFormat = defaultValue(options.vertexFormat, VertexFormat.DEFAULT);

    this._angle = angle;
    this._radius = radius;
    this._stackPartitions = stackPartitions;
    this._slicePartitions = slicePartitions;
    this._vertexFormat = vertexFormat;
}

ConicArcSensorGeometry.fromDimensions = function (options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    var angle = options.angle;
    var radius = options.radius;
    var stackPartitions = options.stackPartitions;
    var slicePartitions = options.slicePartitions;

    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number('angle', angle);
    Check.typeOf.number('radius', radius);
    Check.typeOf.number.greaterThanOrEquals('angle', angle, 0);
    Check.typeOf.number.greaterThanOrEquals('height', height, 0);
    //>>includeEnd('debug');

    return new ConicArcSensorGeometry({
        angle: angle,
        radius: radius,
        stackPartitions: stackPartitions,
        slicePartitions: slicePartitions,
        vertexFormat: options.vertexFormat
    });
};

ConicArcSensorGeometry.createGeometry = function (conicSensorGeometry) {
    console.time('createGeometry');

    var angle = conicSensorGeometry._angle;
    var radius = conicSensorGeometry._radius;
    var stackPartitions = conicSensorGeometry._stackPartitions + 1;
    var slicePartitions = conicSensorGeometry._slicePartitions + 1;
    var vertexFormat = conicSensorGeometry._vertexFormat;

    var attributes = new GeometryAttributes();

    var bottomIndex;

    var numIndices = 3 * (slicePartitions - 1) + 6 * (slicePartitions - 1) * (stackPartitions - 2) + (slicePartitions - 1) * 1 * 3;
    var vertexCount = stackPartitions * slicePartitions;
    var indices = IndexDatatype.createTypedArray(vertexCount, numIndices);
    var positions = new Float64Array(vertexCount * 3 + (slicePartitions - 1) * 3 * 3);

    if (vertexFormat.position) {
        var positionIndex = 0;

        //bottom plat
        var cosTheta = new Array(slicePartitions);
        var sinTheta = new Array(slicePartitions);

        for (var i = 0; i < slicePartitions; i++) {
            var theta = CesiumMath.TWO_PI * i / (slicePartitions - 1);
            cosTheta[i] = cos(theta);
            sinTheta[i] = sin(theta);

            positions[positionIndex++] = 0.0;
            positions[positionIndex++] = 0.0;
            positions[positionIndex++] = -radius;
        }

        for (i = 1; i < stackPartitions; i++) {
            var phi = angle * i / (stackPartitions - 1);
            var sinPhi = sin(phi);

            var xSinPhi = radius * sinPhi;
            var ySinPhi = radius * sinPhi;
            var zCosPhi = radius * cos(phi);

            for (var j = 0; j < slicePartitions; j++) {
                positions[positionIndex++] = cosTheta[j] * xSinPhi;
                positions[positionIndex++] = sinTheta[j] * ySinPhi;
                positions[positionIndex++] = -zCosPhi;
            }
        }

        //side plat
        bottomIndex = positionIndex;
        for (var i = 0; i < slicePartitions - 1; i++) {
            positions[positionIndex++] = 0;
            positions[positionIndex++] = 0;
            positions[positionIndex++] = 0;

            positions[positionIndex++] = positions[bottomIndex - (slicePartitions - i - 1) * 3];
            positions[positionIndex++] = positions[bottomIndex - (slicePartitions - i - 1) * 3 + 1];
            positions[positionIndex++] = positions[bottomIndex - (slicePartitions - i - 1) * 3 + 2];

            positions[positionIndex++] = positions[bottomIndex - (slicePartitions - i) * 3];
            positions[positionIndex++] = positions[bottomIndex - (slicePartitions - i) * 3 + 1];
            positions[positionIndex++] = positions[bottomIndex - (slicePartitions - i) * 3 + 2];
        }

        attributes.position = new GeometryAttribute({
            componentDatatype: ComponentDatatype.DOUBLE,
            componentsPerAttribute: 3,
            values: positions
        });
    }

    var indicesIndex = 0;

    //bottom plat
    for (var j = 0; j < slicePartitions - 1; j++) {
        indices[indicesIndex++] = slicePartitions + j;
        indices[indicesIndex++] = slicePartitions + j + 1;
        indices[indicesIndex++] = j + 1;
    }

    var topOffset;
    var bottomOffset;
    for (var i = 1; i < stackPartitions - 1; i++) {
        topOffset = i * slicePartitions;
        bottomOffset = (i + 1) * slicePartitions;

        for (j = 0; j < slicePartitions - 1; j++) {
            indices[indicesIndex++] = bottomOffset + j;
            indices[indicesIndex++] = bottomOffset + j + 1;
            indices[indicesIndex++] = topOffset + j + 1;

            indices[indicesIndex++] = bottomOffset + j;
            indices[indicesIndex++] = topOffset + j + 1;
            indices[indicesIndex++] = topOffset + j;
        }
    }

    //side plat
    for (var i = 0, len = (slicePartitions - 1) * 3; i < len; i++) {
        indices[indicesIndex++] = i + bottomIndex / 3;
    }

    var geometry = new Geometry({
        attributes: attributes,
        indices: indices,
        primitiveType: PrimitiveType.TRIANGLES,
        boundingSphere: new BoundingSphere(Cartesian3.ZERO, radius)
    });
    geometry = GeometryPipeline.computeNormal(geometry);
    console.timeEnd('createGeometry');
    return geometry;
};

exports.ConicArcSensorGeometry = ConicArcSensorGeometry;

/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});
var BoundingSphere = Cesium.BoundingSphere,
    Cartesian3 = Cesium.Cartesian3,
    ComponentDatatype = Cesium.ComponentDatatype,
    defaultValue = Cesium.defaultValue,
    defined = Cesium.defined,
    DeveloperError = Cesium.DeveloperError,
    Ellipsoid = Cesium.Ellipsoid,
    Geometry = Cesium.Geometry,
    GeometryAttribute = Cesium.GeometryAttribute,
    GeometryAttributes = Cesium.GeometryAttributes,
    IndexDatatype = Cesium.IndexDatatype,
    CesiumMath = Cesium.Math,
    PrimitiveType = Cesium.PrimitiveType;

var defaultRadii = new Cartesian3(1.0, 1.0, 1.0);
var cos = Math.cos;
var sin = Math.sin;

function ConicArcSensorOutlineGeometry(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);

    var angle = options.angle;
    var radius = options.radius;

    var stackPartitions = Math.round(defaultValue(options.stackPartitions, 10));
    var slicePartitions = Math.round(defaultValue(options.slicePartitions, 8));
    var subdivisions = Math.round(defaultValue(options.subdivisions, 128));

    //>>includeStart('debug', pragmas.debug);
    if (stackPartitions < 1) {
        throw new DeveloperError('options.stackPartitions cannot be less than 1');
    }
    if (slicePartitions < 0) {
        throw new DeveloperError('options.slicePartitions cannot be less than 0');
    }
    if (subdivisions < 0) {
        throw new DeveloperError('options.subdivisions must be greater than or equal to zero.');
    }
    //>>includeEnd('debug');

    this._angle = angle;
    this._radius = radius;
    this._stackPartitions = stackPartitions;
    this._slicePartitions = slicePartitions;
    this._subdivisions = subdivisions;
}

ConicArcSensorOutlineGeometry.createGeometry = function (conicSensorGeometry) {

    var angle = conicSensorGeometry._angle;
    var radius = conicSensorGeometry._radius;

    if (radius <= 0 || angle <= 0) {
        return;
    }

    var stackPartitions = conicSensorGeometry._stackPartitions;
    var slicePartitions = conicSensorGeometry._slicePartitions;
    var subdivisions = conicSensorGeometry._subdivisions;

    var indicesSize = subdivisions * (stackPartitions + slicePartitions - 1);
    var positionSize = indicesSize - slicePartitions + 2;
    var positions = new Float64Array(positionSize * 3);
    var indices = IndexDatatype.createTypedArray(positionSize, indicesSize * 2);

    var i;
    var j;
    var theta;
    var phi;
    var cosPhi;
    var sinPhi;
    var index = 0;

    var cosTheta = new Array(subdivisions);
    var sinTheta = new Array(subdivisions);
    for (i = 0; i < subdivisions; i++) {
        theta = CesiumMath.TWO_PI * i / subdivisions;
        cosTheta[i] = cos(theta);
        sinTheta[i] = sin(theta);
    }

    for (i = 1; i < stackPartitions; i++) {
        phi = angle * i / (stackPartitions - 1);
        cosPhi = cos(phi);
        sinPhi = sin(phi);

        for (j = 0; j < subdivisions; j++) {
            positions[index++] = radius * cosTheta[j] * sinPhi;
            positions[index++] = radius * sinTheta[j] * sinPhi;
            positions[index++] = -radius * cosPhi;
        }
    }

    cosTheta.length = slicePartitions;
    sinTheta.length = slicePartitions;
    for (i = 0; i < slicePartitions; i++) {
        theta = CesiumMath.TWO_PI * i / slicePartitions;
        cosTheta[i] = cos(theta);
        sinTheta[i] = sin(theta);
    }

    positions[index++] = 0;
    positions[index++] = 0;
    positions[index++] = -radius;

    for (i = 1; i < subdivisions; i++) {
        phi = angle * i / subdivisions;
        cosPhi = cos(phi);
        sinPhi = sin(phi);

        for (j = 0; j < slicePartitions; j++) {
            positions[index++] = radius * cosTheta[j] * sinPhi;
            positions[index++] = radius * sinTheta[j] * sinPhi;
            positions[index++] = -radius * cosPhi;
        }
    }

    /*positions[index++] = 0;
     positions[index++] = 0;
     positions[index++] = -radii.z;*/

    index = 0;
    for (i = 0; i < stackPartitions - 1; ++i) {
        var topRowOffset = i * subdivisions;
        for (j = 0; j < subdivisions - 1; ++j) {
            indices[index++] = topRowOffset + j;
            indices[index++] = topRowOffset + j + 1;
        }

        indices[index++] = topRowOffset + subdivisions - 1;
        indices[index++] = topRowOffset;
    }

    var sliceOffset = subdivisions * (stackPartitions - 1);
    for (j = 1; j < slicePartitions + 1; ++j) {
        indices[index++] = sliceOffset;
        indices[index++] = sliceOffset + j;
    }

    for (i = 0; i < subdivisions - 2; ++i) {
        var topOffset = i * slicePartitions + 1 + sliceOffset;
        var bottomOffset = (i + 1) * slicePartitions + 1 + sliceOffset;

        for (j = 0; j < slicePartitions - 1; ++j) {
            indices[index++] = bottomOffset + j;
            indices[index++] = topOffset + j;
        }

        indices[index++] = bottomOffset + slicePartitions - 1;
        indices[index++] = topOffset + slicePartitions - 1;
    }

    /*var lastPosition = positions.length / 3 - 1;
     for (j = lastPosition - 1; j > lastPosition - slicePartitions - 1; --j) {
     indices[index++] = lastPosition;
     indices[index++] = j;
     }*/

    var attributes = new GeometryAttributes({
        position: new GeometryAttribute({
            componentDatatype: ComponentDatatype.DOUBLE,
            componentsPerAttribute: 3,
            values: positions
        })
    });

    return new Geometry({
        attributes: attributes,
        indices: indices,
        primitiveType: PrimitiveType.LINES,
        boundingSphere: new BoundingSphere(Cartesian3.ZERO, radius)
    });
};

exports.ConicArcSensorOutlineGeometry = ConicArcSensorOutlineGeometry;

/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});
var defaultValue = Cesium.defaultValue,
    defined = Cesium.defined,
    defineProperties = Object.defineProperties,
    DeveloperError = Cesium.DeveloperError,
    Event = Cesium.Event,
    createMaterialPropertyDescriptor = Cesium.createMaterialPropertyDescriptor,
    createPropertyDescriptor = Cesium.createPropertyDescriptor;

function ConicArcSensorGraphics(options) {
    this._angle = undefined;
    this._angleSubscription = undefined;
    this._radius = undefined;
    this._radiusSubscription = undefined;
    this._stack = undefined;
    this._stackSubscription = undefined;
    this._slice = undefined;
    this._sliceSubscription = undefined;
    this._color = undefined;
    this._colorSubscription = undefined;
    this._show = undefined;
    this._showSubscription = undefined;
    this._fill = undefined;
    this._fillSubscription = undefined;
    this._color = undefined;
    this._colorSubscription = undefined;
    this._material = undefined;
    this._materialSubscription = undefined;
    this._outline = undefined;
    this._outlineSubscription = undefined;
    this._outlineColor = undefined;
    this._outlineColorSubscription = undefined;
    this._outlineWidth = undefined;
    this._outlineWidthSubscription = undefined;
    this._shadows = undefined;
    this._shadowsSubscription = undefined;
    this._distanceDisplayCondition = undefined;
    this._distanceDisplayConditionSubscription = undefined;
    this._definitionChanged = new Event();

    this._gaze = undefined;
    this._gazeSubscription = undefined;

    this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT));
}

defineProperties(ConicArcSensorGraphics.prototype, {
    /**
     * Gets the event that is raised whenever a property or sub-property is changed or modified.
     * @memberof BoxGraphics.prototype
     * @type {Event}
     * @readonly
     */
    definitionChanged: {
        get: function get() {
            return this._definitionChanged;
        }
    },

    /**
     * Gets or sets the boolean Property specifying the visibility of the box.
     * @memberof BoxGraphics.prototype
     * @type {Property}
     * @default true
     */
    show: createPropertyDescriptor('show'),

    angle: createPropertyDescriptor('angle'),

    radius: createPropertyDescriptor('radius'),

    stack: createPropertyDescriptor('stack'),

    slice: createPropertyDescriptor('slice'),

    color: createPropertyDescriptor('color'),

    /**
     * Gets or sets the material used to fill the box.
     * @memberof BoxGraphics.prototype
     * @type {MaterialProperty}
     * @default Color.WHITE
     */
    material: createMaterialPropertyDescriptor('material'),

    /**
     * Gets or sets the boolean Property specifying whether the box is filled with the provided material.
     * @memberof BoxGraphics.prototype
     * @type {Property}
     * @default true
     */
    fill: createPropertyDescriptor('fill'),

    /**
     * Gets or sets the Property specifying whether the box is outlined.
     * @memberof BoxGraphics.prototype
     * @type {Property}
     * @default false
     */
    outline: createPropertyDescriptor('outline'),

    /**
     * Gets or sets the Property specifying the {@link Color} of the outline.
     * @memberof BoxGraphics.prototype
     * @type {Property}
     * @default Color.BLACK
     */
    outlineColor: createPropertyDescriptor('outlineColor'),

    /**
     * Gets or sets the numeric Property specifying the width of the outline.
     * @memberof BoxGraphics.prototype
     * @type {Property}
     * @default 1.0
     */
    outlineWidth: createPropertyDescriptor('outlineWidth'),

    /**
     * Get or sets the enum Property specifying whether the box
     * casts or receives shadows from each light source.
     * @memberof BoxGraphics.prototype
     * @type {Property}
     * @default ShadowMode.DISABLED
     */
    shadows: createPropertyDescriptor('shadows'),

    /**
     * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this box will be displayed.
     * @memberof BoxGraphics.prototype
     * @type {Property}
     */
    distanceDisplayCondition: createPropertyDescriptor('distanceDisplayCondition')
});

ConicArcSensorGraphics.prototype.clone = function (result) {
    if (!defined(result)) {
        return new ConicArcSensorGraphics(this);
    }
    result.angle = this.angle;
    result.radius = this.radius;
    result.stack = this.stack;
    result.slice = this.slice;
    result.show = this.show;
    result.material = this.material;
    result.color = this.color;
    result.fill = this.fill;
    result.outline = this.outline;
    result.outlineColor = this.outlineColor;
    result.outlineWidth = this.outlineWidth;
    result.shadows = this.shadows;
    result.distanceDisplayCondition = this.distanceDisplayCondition;
    result.gaze = this.gaze;
    return result;
};

ConicArcSensorGraphics.prototype.merge = function (source) {
    //>>includeStart('debug', pragmas.debug);
    if (!defined(source)) {
        throw new DeveloperError('source is required.');
    }
    //>>includeEnd('debug');

    this.angle = defaultValue(this.angle, source.angle);
    this.radius = defaultValue(this.radius, source.radius);
    this.stack = defaultValue(this.stack, source.stack);
    this.slice = defaultValue(this.slice, source.slice);
    this.show = defaultValue(this.show, source.show);
    this.color = defaultValue(this.color, source.color);
    this.material = defaultValue(this.material, source.material);
    this.fill = defaultValue(this.fill, source.fill);
    this.outline = defaultValue(this.outline, source.outline);
    this.outlineColor = defaultValue(this.outlineColor, source.outlineColor);
    this.outlineWidth = defaultValue(this.outlineWidth, source.outlineWidth);
    this.shadows = defaultValue(this.shadows, source.shadows);
    this.distanceDisplayCondition = defaultValue(this.distanceDisplayCondition, source.distanceDisplayCondition);
    this.gaze = defaultValue(this.gaze, source.gaze);
};

exports.ConicArcSensorGraphics = ConicArcSensorGraphics;

/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _index = __webpack_require__(5);

Object.keys(_index).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _index[key];
    }
  });
});

/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _RectangularSensorPrimitive = __webpack_require__(0);

var _RectangularSensorGraphics = __webpack_require__(10);

var _RectangularSensorVisualizer = __webpack_require__(11);

var _ConicArcSensorGeometry = __webpack_require__(1);

var _ConicArcSensorOutlineGeometry = __webpack_require__(2);

var _ConicArcSensorGraphics = __webpack_require__(3);

var _ConicArcSensorCollection = __webpack_require__(12);

//rectangularSensor


//conicSensor
Cesium.RectangularSensorPrimitive = _RectangularSensorPrimitive.RectangularSensorPrimitive;
Cesium.RectangularSensorGraphics = _RectangularSensorGraphics.RectangularSensorGraphics;
Cesium.RectangularSensorVisualizer = _RectangularSensorVisualizer.RectangularSensorVisualizer;

//conicSensor
Cesium.ConicArcSensorGeometry = _ConicArcSensorGeometry.ConicArcSensorGeometry;
Cesium.ConicArcSensorOutlineGeometry = _ConicArcSensorOutlineGeometry.ConicArcSensorOutlineGeometry;
Cesium.ConicArcSensorGraphics = _ConicArcSensorGraphics.ConicArcSensorGraphics;
Cesium.ConicArcSensorCollection = _ConicArcSensorCollection.ConicArcSensorCollection;

var DataSourceDisplay = Cesium.DataSourceDisplay;
var originalDefaultVisualizersCallback = DataSourceDisplay.defaultVisualizersCallback;
DataSourceDisplay.defaultVisualizersCallback = function (scene, entityCluster, dataSource) {
    var entities = dataSource.entities;
    var array = originalDefaultVisualizersCallback(scene, entityCluster, dataSource);
    return array.concat([new _RectangularSensorVisualizer.RectangularSensorVisualizer(scene, entities)]);
};

/***/ }),
/* 6 */
/***/ (function(module, exports) {

module.exports = "attribute vec4 position;\r\nattribute vec3 normal;\r\n\r\nvarying vec3 v_position;\r\nvarying vec3 v_positionWC;\r\nvarying vec3 v_positionEC;\r\nvarying vec3 v_normalEC;\r\n\r\nvoid main()\r\n{\r\n    gl_Position = czm_modelViewProjection * position;\r\n    v_position = vec3(position);\r\n    v_positionWC = (czm_model * position).xyz;\r\n    v_positionEC = (czm_modelView * position).xyz;\r\n    v_normalEC = czm_normal * normal;\r\n}"

/***/ }),
/* 7 */
/***/ (function(module, exports) {

module.exports = "#ifdef GL_OES_standard_derivatives\r\n#extension GL_OES_standard_derivatives : enable\r\n#endif\r\n\r\nuniform bool u_showIntersection;\r\nuniform bool u_showThroughEllipsoid;\r\n\r\nuniform float u_radius;\r\nuniform float u_xHalfAngle;\r\nuniform float u_yHalfAngle;\r\nuniform float u_normalDirection;\r\nuniform float u_type;\r\n\r\nvarying vec3 v_position;\r\nvarying vec3 v_positionWC;\r\nvarying vec3 v_positionEC;\r\nvarying vec3 v_normalEC;\r\n\r\nvec4 getColor(float sensorRadius, vec3 pointEC)\r\n{\r\n    czm_materialInput materialInput;\r\n\r\n    vec3 pointMC = (czm_inverseModelView * vec4(pointEC, 1.0)).xyz;\r\n    materialInput.st = sensor2dTextureCoordinates(sensorRadius, pointMC);\r\n    materialInput.str = pointMC / sensorRadius;\r\n\r\n    vec3 positionToEyeEC = -v_positionEC;\r\n    materialInput.positionToEyeEC = positionToEyeEC;\r\n\r\n    vec3 normalEC = normalize(v_normalEC);\r\n    materialInput.normalEC = u_normalDirection * normalEC;\r\n\r\n    czm_material material = czm_getMaterial(materialInput);\r\n\r\n    return mix(czm_phong(normalize(positionToEyeEC), material,czm_lightDirectionEC), vec4(material.diffuse, material.alpha), 0.4);\r\n\r\n}\r\n\r\nbool isOnBoundary(float value, float epsilon)\r\n{\r\n    float width = getIntersectionWidth();\r\n    float tolerance = width * epsilon;\r\n\r\n#ifdef GL_OES_standard_derivatives\r\n    float delta = max(abs(dFdx(value)), abs(dFdy(value)));\r\n    float pixels = width * delta;\r\n    float temp = abs(value);\r\n    // There are a couple things going on here.\r\n    // First we test the value at the current fragment to see if it is within the tolerance.\r\n    // We also want to check if the value of an adjacent pixel is within the tolerance,\r\n    // but we don't want to admit points that are obviously not on the surface.\r\n    // For example, if we are looking for \"value\" to be close to 0, but value is 1 and the adjacent value is 2,\r\n    // then the delta would be 1 and \"temp - delta\" would be \"1 - 1\" which is zero even though neither of\r\n    // the points is close to zero.\r\n    return temp < tolerance && temp < pixels || (delta < 10.0 * tolerance && temp - delta < tolerance && temp < pixels);\r\n#else\r\n    return abs(value) < tolerance;\r\n#endif\r\n}\r\n\r\nvec4 shade(bool isOnBoundary)\r\n{\r\n    if (u_showIntersection && isOnBoundary)\r\n    {\r\n        return getIntersectionColor();\r\n    }\r\n    if(u_type == 1.0){\r\n        return getLineColor();\r\n    }\r\n    return getColor(u_radius, v_positionEC);\r\n}\r\n\r\nfloat ellipsoidSurfaceFunction(vec3 point)\r\n{\r\n    vec3 scaled = czm_ellipsoidInverseRadii * point;\r\n    return dot(scaled, scaled) - 1.0;\r\n}\r\n\r\nvoid main()\r\n{\r\n    vec3 sensorVertexWC = czm_model[3].xyz;      // (0.0, 0.0, 0.0) in model coordinates\r\n    vec3 sensorVertexEC = czm_modelView[3].xyz;  // (0.0, 0.0, 0.0) in model coordinates\r\n\r\n    //vec3 pixDir = normalize(v_position);\r\n    float positionX = v_position.x;\r\n    float positionY = v_position.y;\r\n    float positionZ = v_position.z;\r\n\r\n    vec3 zDir = vec3(0.0, 0.0, 1.0);\r\n    vec3 lineX = vec3(positionX, 0 ,positionZ);\r\n    vec3 lineY = vec3(0, positionY, positionZ);\r\n    float resX = dot(normalize(lineX), zDir);\r\n    if(resX < cos(u_xHalfAngle)-0.00001){\r\n        discard;\r\n    }\r\n    float resY = dot(normalize(lineY), zDir);\r\n    if(resY < cos(u_yHalfAngle)-0.00001){\r\n        discard;\r\n    }\r\n\r\n    float ellipsoidValue = ellipsoidSurfaceFunction(v_positionWC);\r\n\r\n    // Occluded by the ellipsoid?\r\n\tif (!u_showThroughEllipsoid)\r\n\t{\r\n\t    // Discard if in the ellipsoid\r\n\t    // PERFORMANCE_IDEA: A coarse check for ellipsoid intersection could be done on the CPU first.\r\n\t    if (ellipsoidValue < 0.0)\r\n\t    {\r\n            discard;\r\n\t    }\r\n\r\n\t    // Discard if in the sensor's shadow\r\n\t    if (inSensorShadow(sensorVertexWC, v_positionWC))\r\n\t    {\r\n\t        discard;\r\n\t    }\r\n    }\r\n\r\n    // Notes: Each surface functions should have an associated tolerance based on the floating point error.\r\n    bool isOnEllipsoid = isOnBoundary(ellipsoidValue, czm_epsilon3);\r\n    //isOnEllipsoid = false;\r\n    //if((resX >= 0.8 && resX <= 0.81)||(resY >= 0.8 && resY <= 0.81)){\r\n    /*if(false){\r\n        gl_FragColor = vec4(1.0,0.0,0.0,1.0);\r\n    }else{\r\n        gl_FragColor = shade(isOnEllipsoid);\r\n    }\r\n*/\r\n    gl_FragColor = shade(isOnEllipsoid);\r\n\r\n}"

/***/ }),
/* 8 */
/***/ (function(module, exports) {

module.exports = "uniform vec4 u_intersectionColor;\nuniform float u_intersectionWidth;\nuniform vec4 u_lineColor;\n\nbool inSensorShadow(vec3 coneVertexWC, vec3 pointWC)\n{\n    // Diagonal matrix from the unscaled ellipsoid space to the scaled space.    \n    vec3 D = czm_ellipsoidInverseRadii;\n\n    // Sensor vertex in the scaled ellipsoid space\n    vec3 q = D * coneVertexWC;\n    float qMagnitudeSquared = dot(q, q);\n    float test = qMagnitudeSquared - 1.0;\n    \n    // Sensor vertex to fragment vector in the ellipsoid's scaled space\n    vec3 temp = D * pointWC - q;\n    float d = dot(temp, q);\n    \n    // Behind silhouette plane and inside silhouette cone\n    return (d < -test) && (d / length(temp) < -sqrt(test));\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nvec4 getLineColor()\n{\n    return u_lineColor;\n}\n\nvec4 getIntersectionColor()\n{\n    return u_intersectionColor;\n}\n\nfloat getIntersectionWidth()\n{\n    return u_intersectionWidth;\n}\n\nvec2 sensor2dTextureCoordinates(float sensorRadius, vec3 pointMC)\n{\n    // (s, t) both in the range [0, 1]\n    float t = pointMC.z / sensorRadius;\n    float s = 1.0 + (atan(pointMC.y, pointMC.x) / czm_twoPi);\n    s = s - floor(s);\n    \n    return vec2(s, t);\n}\n"

/***/ }),
/* 9 */
/***/ (function(module, exports) {

module.exports = "#ifdef GL_OES_standard_derivatives\r\n#extension GL_OES_standard_derivatives : enable\r\n#endif\r\n\r\nuniform bool u_showIntersection;\r\nuniform bool u_showThroughEllipsoid;\r\n\r\nuniform float u_radius;\r\nuniform float u_xHalfAngle;\r\nuniform float u_yHalfAngle;\r\nuniform float u_normalDirection;\r\nuniform vec4 u_color;\r\n\r\nvarying vec3 v_position;\r\nvarying vec3 v_positionWC;\r\nvarying vec3 v_positionEC;\r\nvarying vec3 v_normalEC;\r\n\r\nvec4 getColor(float sensorRadius, vec3 pointEC)\r\n{\r\n    czm_materialInput materialInput;\r\n\r\n    vec3 pointMC = (czm_inverseModelView * vec4(pointEC, 1.0)).xyz;\r\n    materialInput.st = sensor2dTextureCoordinates(sensorRadius, pointMC);\r\n    materialInput.str = pointMC / sensorRadius;\r\n\r\n    vec3 positionToEyeEC = -v_positionEC;\r\n    materialInput.positionToEyeEC = positionToEyeEC;\r\n\r\n    vec3 normalEC = normalize(v_normalEC);\r\n    materialInput.normalEC = u_normalDirection * normalEC;\r\n\r\n    czm_material material = czm_getMaterial(materialInput);\r\n\r\n    material.diffuse = u_color.rgb;\r\n    material.alpha = u_color.a;\r\n\r\n    return mix(czm_phong(normalize(positionToEyeEC), material,czm_lightDirectionEC), vec4(material.diffuse, material.alpha), 0.4);\r\n\r\n}\r\n\r\nbool isOnBoundary(float value, float epsilon)\r\n{\r\n    float width = getIntersectionWidth();\r\n    float tolerance = width * epsilon;\r\n\r\n#ifdef GL_OES_standard_derivatives\r\n    float delta = max(abs(dFdx(value)), abs(dFdy(value)));\r\n    float pixels = width * delta;\r\n    float temp = abs(value);\r\n    // There are a couple things going on here.\r\n    // First we test the value at the current fragment to see if it is within the tolerance.\r\n    // We also want to check if the value of an adjacent pixel is within the tolerance,\r\n    // but we don't want to admit points that are obviously not on the surface.\r\n    // For example, if we are looking for \"value\" to be close to 0, but value is 1 and the adjacent value is 2,\r\n    // then the delta would be 1 and \"temp - delta\" would be \"1 - 1\" which is zero even though neither of\r\n    // the points is close to zero.\r\n    return temp < tolerance && temp < pixels || (delta < 10.0 * tolerance && temp - delta < tolerance && temp < pixels);\r\n#else\r\n    return abs(value) < tolerance;\r\n#endif\r\n}\r\n\r\nvec4 shade(bool isOnBoundary)\r\n{\r\n    if (u_showIntersection && isOnBoundary)\r\n    {\r\n        return getIntersectionColor();\r\n    }\r\n    return getColor(u_radius, v_positionEC);\r\n}\r\n\r\nfloat ellipsoidSurfaceFunction(vec3 point)\r\n{\r\n    vec3 scaled = czm_ellipsoidInverseRadii * point;\r\n    return dot(scaled, scaled) - 1.0;\r\n}\r\n\r\nvoid main()\r\n{\r\n    vec3 sensorVertexWC = czm_model[3].xyz;      // (0.0, 0.0, 0.0) in model coordinates\r\n    vec3 sensorVertexEC = czm_modelView[3].xyz;  // (0.0, 0.0, 0.0) in model coordinates\r\n\r\n    //vec3 pixDir = normalize(v_position);\r\n    float positionX = v_position.x;\r\n    float positionY = v_position.y;\r\n    float positionZ = v_position.z;\r\n\r\n    vec3 zDir = vec3(0.0, 0.0, 1.0);\r\n    vec3 lineX = vec3(positionX, 0 ,positionZ);\r\n    vec3 lineY = vec3(0, positionY, positionZ);\r\n    float resX = dot(normalize(lineX), zDir);\r\n    if(resX < cos(u_xHalfAngle) - 0.0001){\r\n        discard;\r\n    }\r\n    float resY = dot(normalize(lineY), zDir);\r\n    if(resY < cos(u_yHalfAngle)- 0.0001){\r\n        discard;\r\n    }\r\n\r\n    float ellipsoidValue = ellipsoidSurfaceFunction(v_positionWC);\r\n\r\n    // Occluded by the ellipsoid?\r\n\tif (!u_showThroughEllipsoid)\r\n\t{\r\n\t    // Discard if in the ellipsoid\r\n\t    // PERFORMANCE_IDEA: A coarse check for ellipsoid intersection could be done on the CPU first.\r\n\t    if (ellipsoidValue < 0.0)\r\n\t    {\r\n            discard;\r\n\t    }\r\n\r\n\t    // Discard if in the sensor's shadow\r\n\t    if (inSensorShadow(sensorVertexWC, v_positionWC))\r\n\t    {\r\n\t        discard;\r\n\t    }\r\n    }\r\n\r\n    // Notes: Each surface functions should have an associated tolerance based on the floating point error.\r\n    bool isOnEllipsoid = isOnBoundary(ellipsoidValue, czm_epsilon3);\r\n    gl_FragColor = shade(isOnEllipsoid);\r\n\r\n}"

/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});
var defaultValue = Cesium.defaultValue;
var defined = Cesium.defined;
var defineProperties = Object.defineProperties;
var DeveloperError = Cesium.DeveloperError;
var Event = Cesium.Event;
var createMaterialPropertyDescriptor = Cesium.createMaterialPropertyDescriptor;
var createPropertyDescriptor = Cesium.createPropertyDescriptor;

function RectangularSensorGraphics(options) {
    this._show = undefined;
    this._radius = undefined;
    this._xHalfAngle = undefined;
    this._yHalfAngle = undefined;
    this._lineColor = undefined;
    this._showSectorLines = undefined;
    this._showSectorSegmentLines = undefined;
    this._showLateralSurfaces = undefined;
    this._material = undefined;
    this._showDomeSurfaces = undefined;
    this._showDomeLines = undefined;
    this._showIntersection = undefined;
    this._intersectionColor = undefined;
    this._intersectionWidth = undefined;
    this._showThroughEllipsoid = undefined;
    this._gaze = undefined;
    this._showScanPlane = undefined;
    this._scanPlaneColor = undefined;
    this._scanPlaneMode = undefined;
    this._scanPlaneRate = undefined;
    this._definitionChanged = new Event();
    this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT));
}

defineProperties(RectangularSensorGraphics.prototype, {
    definitionChanged: {
        get: function get() {
            return this._definitionChanged;
        }
    },

    show: createPropertyDescriptor('show'),
    radius: createPropertyDescriptor('radius'),
    xHalfAngle: createPropertyDescriptor('xHalfAngle'),
    yHalfAngle: createPropertyDescriptor('yHalfAngle'),
    lineColor: createPropertyDescriptor('lineColor'),
    showSectorLines: createPropertyDescriptor('showSectorLines'),
    showSectorSegmentLines: createPropertyDescriptor('showSectorSegmentLines'),
    showLateralSurfaces: createPropertyDescriptor('showLateralSurfaces'),
    material: createMaterialPropertyDescriptor('material'),
    showDomeSurfaces: createPropertyDescriptor('showDomeSurfaces'),
    showDomeLines: createPropertyDescriptor('showDomeLines '),
    showIntersection: createPropertyDescriptor('showIntersection'),
    intersectionColor: createPropertyDescriptor('intersectionColor'),
    intersectionWidth: createPropertyDescriptor('intersectionWidth'),
    showThroughEllipsoid: createPropertyDescriptor('showThroughEllipsoid'),
    gaze: createPropertyDescriptor('gaze'),
    showScanPlane: createPropertyDescriptor('showScanPlane'),
    scanPlaneColor: createPropertyDescriptor('scanPlaneColor'),
    scanPlaneMode: createPropertyDescriptor('scanPlaneMode'),
    scanPlaneRate: createPropertyDescriptor('scanPlaneRate')
});

RectangularSensorGraphics.prototype.clone = function (result) {
    if (!defined(result)) {
        result = new RectangularSensorGraphics();
    }

    result.show = this.show;
    result.radius = this.radius;
    result.xHalfAngle = this.xHalfAngle;
    result.yHalfAngle = this.yHalfAngle;
    result.lineColor = this.lineColor;
    result.showSectorLines = this.showSectorLines;
    result.showSectorSegmentLines = this.showSectorSegmentLines;
    result.showLateralSurfaces = this.showLateralSurfaces;
    result.material = this.material;
    result.showDomeSurfaces = this.showDomeSurfaces;
    result.showDomeLines = this.showDomeLines;
    result.showIntersection = this.showIntersection;
    result.intersectionColor = this.intersectionColor;
    result.intersectionWidth = this.intersectionWidth;
    result.showThroughEllipsoid = this.showThroughEllipsoid;
    result.gaze = this.gaze;
    result.showScanPlane = this.showScanPlane;
    result.scanPlaneColor = this.scanPlaneColor;
    result.scanPlaneMode = this.scanPlaneMode;
    result.scanPlaneRate = this.scanPlaneRate;

    return result;
};

RectangularSensorGraphics.prototype.merge = function (source) {
    if (!defined(source)) {
        throw new DeveloperError('source is required.');
    }

    this.show = defaultValue(this.show, source.show);
    this.radius = defaultValue(this.radius, source.radius);
    this.xHalfAngle = defaultValue(this.xHalfAngle, source.xHalfAngle);
    this.yHalfAngle = defaultValue(this.yHalfAngle, source.yHalfAngle);
    this.lineColor = defaultValue(this.lineColor, source.lineColor);
    this.showSectorLines = defaultValue(this.showSectorLines, source.showSectorLines);
    this.showSectorSegmentLines = defaultValue(this.showSectorSegmentLines, source.showSectorSegmentLines);
    this.showLateralSurfaces = defaultValue(this.showLateralSurfaces, source.showLateralSurfaces);
    this.material = defaultValue(this.material, source.material);
    this.showDomeSurfaces = defaultValue(this.showDomeSurfaces, source.showDomeSurfaces);
    this.showDomeLines = defaultValue(this.showDomeLines, source.showDomeLines);
    this.showIntersection = defaultValue(this.showIntersection, source.showIntersection);
    this.intersectionColor = defaultValue(this.intersectionColor, source.intersectionColor);
    this.intersectionWidth = defaultValue(this.intersectionWidth, source.intersectionWidth);
    this.showThroughEllipsoid = defaultValue(this.showThroughEllipsoid, source.showThroughEllipsoid);
    this.gaze = defaultValue(this.gaze, source.gaze);
    this.showScanPlane = defaultValue(this.showScanPlane, source.showScanPlane);
    this.scanPlaneColor = defaultValue(this.scanPlaneColor, source.scanPlaneColor);
    this.scanPlaneMode = defaultValue(this.scanPlaneMode, source.scanPlaneMode);
    this.scanPlaneRate = defaultValue(this.scanPlaneRate, source.scanPlaneRate);
};

exports.RectangularSensorGraphics = RectangularSensorGraphics;

/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.RectangularSensorVisualizer = undefined;

var _RectangularSensorPrimitive = __webpack_require__(0);

var AssociativeArray = Cesium.AssociativeArray;
var Cartesian3 = Cesium.Cartesian3;
var Color = Cesium.Color;
var defined = Cesium.defined;
var destroyObject = Cesium.destroyObject;
var DeveloperError = Cesium.DeveloperError;
var Matrix3 = Cesium.Matrix3;
var Matrix4 = Cesium.Matrix4;
var Quaternion = Cesium.Quaternion;
var MaterialProperty = Cesium.MaterialProperty;
var Property = Cesium.Property;

var matrix3Scratch = new Matrix3();
var matrix4Scratch = new Matrix4();
var cachedPosition = new Cartesian3();
var cachedGazePosition = new Cartesian3();
var cachedOrientation = new Quaternion();
var diffVectorScratch = new Cartesian3();
var orientationScratch = new Quaternion();

function removePrimitive(entity, hash, primitives) {
    var data = hash[entity.id];
    if (defined(data)) {
        var primitive = data.primitive;
        primitives.remove(primitive);
        if (!primitive.isDestroyed()) {
            primitive.destroy();
        }
        delete hash[entity.id];
    }
};

var RectangularSensorVisualizer = function RectangularSensorVisualizer(scene, entityCollection) {
    // >>includeStart('debug', pragmas.debug);
    if (!defined(scene)) {
        throw new DeveloperError('scene is required.');
    }
    if (!defined(entityCollection)) {
        throw new DeveloperError('entityCollection is required.');
    }
    // >>includeEnd('debug');

    entityCollection.collectionChanged.addEventListener(RectangularSensorVisualizer.prototype._onCollectionChanged, this);

    this._scene = scene;
    this._primitives = scene.primitives;
    this._entityCollection = entityCollection;
    this._hash = {};
    this._entitiesToVisualize = new AssociativeArray();

    this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
};

/**
 * Updates the primitives created by this visualizer to match their
 * Entity counterpart at the given time.
 *
 * @param {JulianDate} time The time to update to.
 * @returns {Boolean} This function always returns true.
 */
RectangularSensorVisualizer.prototype.update = function (time) {
    // >>includeStart('debug', pragmas.debug);
    if (!defined(time)) {
        throw new DeveloperError('time is required.');
    }
    // >>includeEnd('debug');

    var entities = this._entitiesToVisualize.values;
    var hash = this._hash;
    var primitives = this._primitives;

    for (var i = 0, len = entities.length; i < len; i++) {
        var entity = entities[i];
        var rectangularSensorGraphics = entity._rectangularSensor;

        var position;
        var orientation;
        var radius;
        var xHalfAngle;
        var yHalfAngle;
        var data = hash[entity.id];
        var show = entity.isShowing && entity.isAvailable(time) && Property.getValueOrDefault(rectangularSensorGraphics._show, time, true);

        if (show) {
            position = Property.getValueOrUndefined(entity._position, time, cachedPosition);
            orientation = Property.getValueOrUndefined(entity._orientation, time, cachedOrientation);
            radius = Property.getValueOrUndefined(rectangularSensorGraphics._radius, time);
            xHalfAngle = Property.getValueOrUndefined(rectangularSensorGraphics._xHalfAngle, time);
            yHalfAngle = Property.getValueOrUndefined(rectangularSensorGraphics._yHalfAngle, time);
            show = defined(position) && defined(xHalfAngle) && defined(yHalfAngle);
        }

        if (!show) {
            // don't bother creating or updating anything else
            if (defined(data)) {
                data.primitive.show = false;
            }
            continue;
        }

        var primitive = defined(data) ? data.primitive : undefined;
        if (!defined(primitive)) {
            primitive = new _RectangularSensorPrimitive.RectangularSensorPrimitive();
            primitive.id = entity;
            primitives.add(primitive);

            data = {
                primitive: primitive,
                position: undefined,
                orientation: undefined
            };
            hash[entity.id] = data;
        }

        var gaze = Property.getValueOrUndefined(rectangularSensorGraphics._gaze, time);
        if (defined(gaze)) {

            var targetPosition = Property.getValueOrUndefined(gaze._position, time, cachedGazePosition);

            if (!defined(position) || !defined(targetPosition)) {
                continue;
            }

            var diffVector = Cartesian3.subtract(position, targetPosition, diffVectorScratch);
            var rotate = Cartesian3.angleBetween(Cesium.Cartesian3.UNIT_Z, diffVector);
            var cross = Cartesian3.cross(Cesium.Cartesian3.UNIT_Z, diffVector, diffVectorScratch);
            var orientation = Quaternion.fromAxisAngle(cross, rotate - Math.PI, orientationScratch);

            //replace original radius
            radius = Cartesian3.distance(position, targetPosition);
            primitive.modelMatrix = Matrix4.fromRotationTranslation(Matrix3.fromQuaternion(orientation, matrix3Scratch), position, primitive.modelMatrix);
        } else {
            if (!Cartesian3.equals(position, data.position) || !Quaternion.equals(orientation, data.orientation)) {
                if (defined(orientation)) {
                    primitive.modelMatrix = Matrix4.fromRotationTranslation(Matrix3.fromQuaternion(orientation, matrix3Scratch), position, primitive.modelMatrix);
                    data.position = Cartesian3.clone(position, data.position);
                    data.orientation = Quaternion.clone(orientation, data.orientation);
                } else {
                    primitive.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(position);
                    data.position = Cartesian3.clone(position, data.position);
                }
            }
        }

        primitive.show = true;
        primitive.gaze = gaze;
        primitive.radius = radius;
        primitive.xHalfAngle = xHalfAngle;
        primitive.yHalfAngle = yHalfAngle;
        primitive.lineColor = Property.getValueOrDefault(rectangularSensorGraphics._lineColor, time, Color.WHITE);
        primitive.showSectorLines = Property.getValueOrDefault(rectangularSensorGraphics._showSectorLines, time, true);
        primitive.showSectorSegmentLines = Property.getValueOrDefault(rectangularSensorGraphics._showSectorSegmentLines, time, true);
        primitive.showLateralSurfaces = Property.getValueOrDefault(rectangularSensorGraphics._showLateralSurfaces, time, true);
        primitive.material = MaterialProperty.getValue(time, rectangularSensorGraphics._material, primitive.material);
        primitive.showDomeSurfaces = Property.getValueOrDefault(rectangularSensorGraphics._showDomeSurfaces, time, true);
        primitive.showDomeLines = Property.getValueOrDefault(rectangularSensorGraphics._showDomeLines, time, true);
        primitive.showIntersection = Property.getValueOrDefault(rectangularSensorGraphics._showIntersection, time, true);
        primitive.intersectionColor = Property.getValueOrDefault(rectangularSensorGraphics._intersectionColor, time, Color.WHITE);
        primitive.intersectionWidth = Property.getValueOrDefault(rectangularSensorGraphics._intersectionWidth, time, 1);
        primitive.showThroughEllipsoid = Property.getValueOrDefault(rectangularSensorGraphics._showThroughEllipsoid, time, true);
        primitive.scanPlaneMode = Property.getValueOrDefault(rectangularSensorGraphics._scanPlaneMode, time);
        primitive.scanPlaneColor = Property.getValueOrDefault(rectangularSensorGraphics._scanPlaneColor, time, Color.WHITE);
        primitive.showScanPlane = Property.getValueOrDefault(rectangularSensorGraphics._showScanPlane, time, true);
        primitive.scanPlaneRate = Property.getValueOrDefault(rectangularSensorGraphics._scanPlaneRate, time, 1);
    }
    return true;
};

/**
 * Returns true if this object was destroyed; otherwise, false.
 *
 * @returns {Boolean} True if this object was destroyed; otherwise, false.
 */
RectangularSensorVisualizer.prototype.isDestroyed = function () {
    return false;
};

/**
 * Removes and destroys all primitives created by this instance.
 */
RectangularSensorVisualizer.prototype.destroy = function () {
    var entities = this._entitiesToVisualize.values;
    var hash = this._hash;
    var primitives = this._primitives;
    for (var i = entities.length - 1; i > -1; i--) {
        removePrimitive(entities[i], hash, primitives);
    }
    return destroyObject(this);
};

/**
 * @private
 */
RectangularSensorVisualizer.prototype._onCollectionChanged = function (entityCollection, added, removed, changed) {
    var i;
    var entity;
    var entities = this._entitiesToVisualize;
    var hash = this._hash;
    var primitives = this._primitives;

    for (i = added.length - 1; i > -1; i--) {
        entity = added[i];
        if (defined(entity._rectangularSensor) && defined(entity._position)) {
            entities.set(entity.id, entity);
        }
    }

    for (i = changed.length - 1; i > -1; i--) {
        entity = changed[i];
        if (defined(entity._rectangularSensor) && defined(entity._position)) {
            entities.set(entity.id, entity);
        } else {
            removePrimitive(entity, hash, primitives);
            entities.remove(entity.id);
        }
    }

    for (i = removed.length - 1; i > -1; i--) {
        entity = removed[i];
        removePrimitive(entity, hash, primitives);
        entities.remove(entity.id);
    }
};

exports.RectangularSensorVisualizer = RectangularSensorVisualizer;

/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.ConicArcSensorCollection = undefined;

var _ConicArcSensorGeometry = __webpack_require__(1);

var _ConicArcSensorOutlineGeometry = __webpack_require__(2);

var _ConicArcSensor = __webpack_require__(13);

var defaultValue = Cesium.defaultValue;
var defined = Cesium.defined;
var Viewer = Cesium.Viewer;
var Transforms = Cesium.Transforms;
var DeveloperError = Cesium.DeveloperError;
var ColorGeometryInstanceAttribute = Cesium.ColorGeometryInstanceAttribute;
var Color = Cesium.Color;
var Primitive = Cesium.Primitive;
var PerInstanceColorAppearance = Cesium.PerInstanceColorAppearance;
var Cartesian3 = Cesium.Cartesian3;
var VertexFormat = Cesium.VertexFormat;
var Quaternion = Cesium.Quaternion;
var Matrix3 = Cesium.Matrix3;
var Matrix4 = Cesium.Matrix4;
var Property = Cesium.Property;
var Event = Cesium.Event;
var DistanceDisplayCondition = Cesium.DistanceDisplayCondition;
var DistanceDisplayConditionGeometryInstanceAttribute = Cesium.DistanceDisplayConditionGeometryInstanceAttribute;

function ConicArcSensorCollection(viewer) {
    var self = this;
    if (!defined(viewer)) {
        throw new DeveloperError('viewer is required.');
    }

    this._viewer = viewer;

    var scene = viewer.scene;
    this._scene = scene;

    var clock = viewer.clock;
    this._clock = clock;

    this._primitives = scene.primitives;
    this._primitive = undefined;
    this._outlinePrimitive = undefined;

    this._conicArcSensorCollection = [];

    clock.onTick.addEventListener(function () {
        self.update();
    });
}

var matrix3Scratch = new Matrix3();
var matrix4Scratch = new Matrix4();
var positionScratch = new Cartesian3();
var targetPositionScratch = new Cartesian3();
var diffVectorScratch = new Cartesian3();
var orientationScratch = new Quaternion();

ConicArcSensorCollection.prototype.add = function (conicArcSensor) {

    if (!(conicArcSensor instanceof _ConicArcSensor.ConicArcSensor)) {
        conicArcSensor = new _ConicArcSensor.ConicArcSensor(conicArcSensor);
    }

    this._conicArcSensorCollection.push(conicArcSensor);

    return conicArcSensor;
};

ConicArcSensorCollection.prototype.remove = function (conicArcSensor) {
    var index = this._conicArcSensorCollection.indexOf(conicArcSensor);
    if (index !== -1) {
        this._conicArcSensorCollection.splice(index, 1);
    }
};

ConicArcSensorCollection.prototype.removeAll = function () {
    this._conicArcSensorCollection.length = 0;
};

ConicArcSensorCollection.prototype.update = function () {
    var time = this._clock.currentTime;

    var conicArcSensorCollection = this._conicArcSensorCollection;
    var primitives = this._primitives;
    var primitive = this._primitive;
    var outlinePrimitive = this._outlinePrimitive;
    var instances = [];
    var outlineInstances = [];

    if (defined(primitive)) {
        primitives.removeAndDestroy(primitive);
    }
    if (defined(outlinePrimitive)) {
        primitives.removeAndDestroy(outlinePrimitive);
    }

    for (var i = 0, len = conicArcSensorCollection.length; i < len; i++) {
        var entity = conicArcSensorCollection[i];
        var conicArcSensor = entity._conicArcSensor;

        if (!Property.getValueOrDefault(conicArcSensor.show, time, true)) {
            continue;
        }

        var angle = conicArcSensor.angle;
        var radius = conicArcSensor.radius;
        var stack = conicArcSensor.stack;
        var slice = conicArcSensor.slice;

        if (!defined(angle)) {
            continue;
        }

        var show = Property.getValueOrDefault(entity.show, time, true);
        if (!show) {
            continue;
        }

        var position = Property.getValueOrUndefined(entity.position, time, positionScratch);

        if (!defined(position)) {
            continue;
        }

        var modelMatrix;
        var gaze = conicArcSensor.gaze;
        if (defined(gaze)) {
            //ignore original orientation
            var targetPosition = Property.getValueOrUndefined(gaze.position, time, targetPositionScratch);

            if (!defined(position) || !defined(targetPosition)) {
                continue;
            }

            var diffVector = Cartesian3.subtract(position, targetPosition, diffVectorScratch);
            var rotate = Cartesian3.angleBetween(Cesium.Cartesian3.UNIT_Z, diffVector);
            var cross = Cartesian3.cross(Cesium.Cartesian3.UNIT_Z, diffVector, diffVectorScratch);
            //朝上
            //var orientation = Quaternion.fromAxisAngle(cross, (rotate - Math.PI), orientationScratch);
            var orientation = Quaternion.fromAxisAngle(cross, rotate, orientationScratch);

            //replace original dimensions
            var distance = Cartesian3.distance(position, targetPosition);

            radius = 1;
            modelMatrix = Matrix4.fromRotationTranslation(Cesium.Matrix3.multiplyByScalar(Matrix3.fromQuaternion(orientation, matrix3Scratch), distance, matrix3Scratch), position, matrix4Scratch);
        } else {
            var orientation = Property.getValueOrUndefined(entity.orientation, time, orientationScratch);
            if (!defined(orientation)) {
                modelMatrix = Transforms.eastNorthUpToFixedFrame(position, undefined, matrix4Scratch);
            } else {
                modelMatrix = Matrix4.fromRotationTranslation(Matrix3.fromQuaternion(orientation, matrix3Scratch), position, matrix4Scratch);
            }
        }

        if (!defined(modelMatrix)) {
            continue;
        }

        var geometry = entity._geometry;
        if (!defined(geometry)) {
            var conic;
            conic = new _ConicArcSensorGeometry.ConicArcSensorGeometry({
                vertexFormat: Cesium.VertexFormat.POSITION_AND_NORMAL,
                angle: angle,
                radius: radius,
                stackPartitions: stack,
                slicePartitions: slice
            });
            entity._geometry = _ConicArcSensorGeometry.ConicArcSensorGeometry.createGeometry(conic);
            geometry = entity._geometry;
        }

        //var distanceDisplayCondition = Property.getValueOrDefault(conicArcSensor.distanceDisplayCondition, time, entity._distanceDisplayCondition);
        //var distanceDisplayConditionAttribute = DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(distanceDisplayCondition);
        //var shadows = Property.getValueOrDefault(conicArcSensor.shadows, time, ShadowMode.DISABLED);
        var color = conicArcSensor.color;
        var outline = conicArcSensor.outline;
        var outlineWidth = conicArcSensor.outlineWidth;
        if (!defined(outlineWidth)) {
            outlineWidth = 1;
        }
        var outlineColor = conicArcSensor.outlineColor;
        if (!defined(outlineColor)) {
            outlineColor = Color.WHITE;
        }

        var instance = new Cesium.GeometryInstance({
            geometry: geometry,
            modelMatrix: modelMatrix,
            attributes: {
                color: Cesium.ColorGeometryInstanceAttribute.fromColor(color)
                //distanceDisplayCondition: distanceDisplayConditionAttribute
            }
        });
        instances.push(instance);

        if (outline) {
            var outlineGeometry = entity._outlineGeometry;
            if (!defined(outlineGeometry)) {
                var conicOutline;
                conicOutline = new _ConicArcSensorOutlineGeometry.ConicArcSensorOutlineGeometry({
                    vertexFormat: Cesium.VertexFormat.POSITION_ONLY,
                    angle: angle,
                    radius: radius
                });
                entity._outlineGeometry = _ConicArcSensorOutlineGeometry.ConicArcSensorOutlineGeometry.createGeometry(conicOutline);
                outlineGeometry = entity._outlineGeometry;
            }

            var instance = new Cesium.GeometryInstance({
                geometry: outlineGeometry,
                modelMatrix: modelMatrix,
                attributes: {
                    color: Cesium.ColorGeometryInstanceAttribute.fromColor(outlineColor)
                    //distanceDisplayCondition: distanceDisplayConditionAttribute
                }
            });
            outlineInstances.push(instance);
        }
    }

    if (instances.length > 0) {
        this._primitive = this._primitives.add(new Primitive({
            asynchronous: false,
            geometryInstances: instances,
            appearance: new PerInstanceColorAppearance({
                flat: false,
                translucent: true,
                closed: true
            })
        }));
    }

    if (outlineInstances.length > 0) {
        this._outlinePrimitive = this._primitives.add(new Primitive({
            asynchronous: false,
            geometryInstances: outlineInstances,
            appearance: new PerInstanceColorAppearance({
                flat: true,
                translucent: true,
                renderState: {
                    lineWidth: this._scene.clampLineWidth(outlineWidth)
                }
            })
        }));
    }
};

exports.ConicArcSensorCollection = ConicArcSensorCollection;

/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.ConicArcSensor = undefined;

var _ConicArcSensorGraphics = __webpack_require__(3);

var Entity = Cesium.Entity;
var Event = Cesium.Event;
var ConstantPositionProperty = Cesium.ConstantPositionProperty;
var createPropertyDescriptor = Cesium.createPropertyDescriptor;
var DistanceDisplayCondition = Cesium.DistanceDisplayCondition;
var DistanceDisplayConditionGeometryInstanceAttribute = Cesium.DistanceDisplayConditionGeometryInstanceAttribute;

function createConstantPositionProperty(value) {
    return new ConstantPositionProperty(value);
}

function createPositionPropertyDescriptor(name) {
    return createPropertyDescriptor(name, undefined, createConstantPositionProperty);
}

function ConicArcSensor(options) {
    options = options || {};

    this._position = undefined;
    this._orientation = undefined;
    this._show = undefined;

    var conicArcSensor = options.conicArcSensor;
    if (!(conicArcSensor instanceof _ConicArcSensorGraphics.ConicArcSensorGraphics)) {
        conicArcSensor = new _ConicArcSensorGraphics.ConicArcSensorGraphics(conicArcSensor);
    }
    this._conicArcSensor = conicArcSensor;

    this._distanceDisplayCondition = new DistanceDisplayCondition();
    this._geometry = undefined;
    this._outlineGeometry = undefined;

    this._definitionChanged = new Event();

    this.merge(options);
}

Object.defineProperties(ConicArcSensor.prototype, {
    position: createPositionPropertyDescriptor('position'),
    orientation: createPropertyDescriptor('orientation'),
    show: createPropertyDescriptor('show')
});

ConicArcSensor.prototype.merge = function (options) {
    this.position = options.position;
    this.orientation = options.orientation;
    this.show = options.show;
};

ConicArcSensor.prototype.gazeAt = function (entity) {
    if (entity instanceof Entity) {
        this._conicArcSensor.gaze = entity;
    }
};

exports.ConicArcSensor = ConicArcSensor;

/***/ })
/******/ ]);
});;
///<jscompress sourcefile="Event.js" />
VFG.Event=function(viewer){
	this.viewer=viewer;
	this.init();
}

/**
 * 初始化
 */
VFG.Event.prototype.init=function(){
	var _this=this;
	_this.handler = new Cesium.ScreenSpaceEventHandler(_this.viewer.scene.canvas);
	_this.handler.setInputAction(function (movement) {
		if(_this.LEFT_CLICK){
			_this.LEFT_CLICK(movement);
		}
    },Cesium.ScreenSpaceEventType.LEFT_CLICK)
    
	_this.handler.setInputAction(function (movement) {
		if(_this.MOUSE_MOVE){
			_this.MOUSE_MOVE(movement);
		}
    },Cesium.ScreenSpaceEventType.MOUSE_MOVE )   
    
    
	_this.handler.setInputAction(function (movement) {
		if(_this.RIGHT_CLICK){
			_this.RIGHT_CLICK(movement);
		}
    },Cesium.ScreenSpaceEventType.RIGHT_CLICK)    
    
    
	_this.handler.setInputAction(function (movement) {
		if(_this.LEFT_DOWN){
			_this.LEFT_DOWN(movement);
		}
    },Cesium.ScreenSpaceEventType.LEFT_DOWN) 
    
	_this.handler.setInputAction(function (movement) {
		if(_this.MIDDLE_DOWN){
			_this.MIDDLE_DOWN(movement);
		}
    },Cesium.ScreenSpaceEventType.MIDDLE_DOWN)  
     
}

VFG.Event.prototype.on=function(EventType,FUNC){
	if('LEFT_CLICK'==EventType){
		this.LEFT_CLICK=FUNC
	}
	if('MOUSE_MOVE'==EventType){
		this.MOUSE_MOVE=FUNC
	}
	if('RIGHT_CLICK'==EventType){
		this.RIGHT_CLICK=FUNC
	}
	if('LEFT_DOWN'==EventType){
		this.LEFT_DOWN=FUNC
	}
	if('MIDDLE_DOWN'==EventType){
		this.MIDDLE_DOWN=FUNC
	}
}

VFG.Event.prototype.remove=function(EventType){
	if('LEFT_CLICK'==EventType){
		this.LEFT_CLICK=null
	}
	if('MOUSE_MOVE'==EventType){
		this.MOUSE_MOVE=null
	}
	if('RIGHT_CLICK'==EventType){
		this.RIGHT_CLICK=null
	}
}



VFG.Event.prototype.destroy=function(){
	var _this = this;
	if(_this.LEFT_CLICK){
		_this.LEFT_CLICK=null;
		delete this.LEFT_CLICK
	}
	if(_this.MOUSE_MOVE){
		_this.MOUSE_MOVE=null;
		delete this.MOUSE_MOVE
	}
	if(_this.RIGHT_CLICK){
		_this.RIGHT_CLICK=null;
		delete this.RIGHT_CLICK
	}
	if(_this.handler){
		_this.handler.destroy();
		delete this.handler
	}
	delete this.viewer
	return Cesium.destroyObject(this);
}
;
///<jscompress sourcefile="Layer.js" />
!function(e, t) {
	"object" == typeof exports && "object" == typeof module ? module.exports = t(require("VFG"))
			: "function" == typeof define && define.amd ? define([ "VFG" ],
					t)
					: "object" == typeof exports ? exports.VFGVFGWin = t(require("VFG"))
							: e.VFGVFGWin = t(e.VFG)
}("undefined" != typeof self ? self : this, function(VFG) {
	function _(viewer,option) {
		this.viewer = viewer;
		this.option = Cesium.defaultValue(option, Cesium.defaultValue.EMPTY_OBJECT);
		this.position=option.position;
		this.layerIndex=option.index;
		this.layero=option.layero;
		this.width;
		this.height;
		this.init();
	}
	_.prototype.init= function() {
		var _this=this;
		var cartesian2=Cesium.SceneTransforms.wgs84ToWindowCoordinates(_this.viewer.scene, _this.position);
		if (Cesium.defined(cartesian2)){
			_this.width=(layui.$(_this.layero).css('width').replace('px','')*1)/2;
			_this.height=(layui.$(_this.layero).css('height').replace('px','')*1)+30;
			layer.style(_this.layerIndex, {
				left:(cartesian2.x-_this.width)+'px',
				top:(cartesian2.y-_this.height)+'px'
			});
		}
    	_this.event=function(){
    		var cartesian2=Cesium.SceneTransforms.wgs84ToWindowCoordinates(_this.viewer.scene, _this.position);
    		if (Cesium.defined(cartesian2)){
        		layer.style(_this.layerIndex, {
    				left:(cartesian2.x+200-_this.width)+'px',
    				top:(cartesian2.y-_this.height)+'px'
        		});
    		}
    	}
    	_this.viewer.scene.postRender.addEventListener(_this.event);
	};
	_.prototype.update = function(position) {
		var _this = this;
		if(position){
			_this.position=position;
		}
	};
	_.prototype.destroy = function() {
		var _this = this;
		if(_this.event){
			_this.viewer.scene.postRender.removeEventListener(_this.event);
		}
		delete this.viewer,
		delete this.option,
		delete this.position,
		delete this.layerIndex;
		delete this.layero;
		delete this.width;
		delete this.height;
		return Cesium.destroyObject(this);
	};
	VFG.Layer= _;
});
///<jscompress sourcefile="Listener.js" />
/**
 * viewer
 * option{
 * 	position:{
 * 		x:经度
 * 		y:维度
 * 		z:高度
 * 	},
 *  callBack:fun(e)回调函数
 * }
 * 
 */
VFG.Listener=function(viewer,option){
	this.option = Cesium.defaultValue(option, Cesium.defaultValue.EMPTY_OBJECT);
	if (!option) {
		console.log('参数必填!');
		return;
	}
	if (!viewer) {
		console.log('参数必填!');
		return;
	}
	this.option = option;
	this.viewer = viewer;
	this.id=option.id;
	
	this.position;
	if(VFG.Point.getById(this.id)){
		this.position =VFG.Point.getById(this.id).position.getValue();
	}else{
		this.position = Cesium.Cartesian3.fromDegrees(option.position.x*1, option.position.y*1, option.position.z*1);
	}
	
//	this.position = option.position;
	this.callBack = option.callBack;
	if(!this.position){
		console.log('参数必填!');
		return;
	}
	this.init();
}

/**
 * 初始化
 */
VFG.Listener.prototype.init=function(){
	var _this=this;
	if(_this.position){
		_this.event=function(){
			var cartesian2=Cesium.SceneTransforms.wgs84ToWindowCoordinates(_this.viewer.scene, _this.position);
			if (Cesium.defined(cartesian2)){
				if(_this.callBack){
					_this.callBack(cartesian2);
				}
			}
		}
		_this.viewer.scene.postRender.addEventListener(_this.event);
	}else{
		console.log('初始化失败，检测是否有效经纬度!!!');
	}
}

VFG.Listener.prototype.update=function(position){
	var _this=this;
	if(position){
		_this.position= Cesium.Cartesian3.fromDegrees(option.position.x*1, option.position.y*1, option.position.z*1);
	}
}

/**
 * 销毁
 */
VFG.Listener.prototype.destroy=function(){
	var _this = this;
	if(_this.event){
		_this.viewer.scene.postRender.removeEventListener(_this.event);
	}
	delete this.option,
	delete this.callBack,
	delete this.viewer,
	delete this.position;
	return Cesium.destroyObject(this);
}
;
///<jscompress sourcefile="Popup.js" />
VFG.Popup=function(viewer, options) {
	this.viewer = viewer;
	this.options = options;
	this.id = this.options.id|| VFG.Util.getUuid();
	this.position=options.position;
	this.cartesian3=VFG.Util.getLnLaToC3(this.position);
	this.html='<div style="position: absolute;bottom: -16px;border: 8px solid transparent;border-top-color:#353d45;left: 50%;margin-left: -8px;"></div><div id='+this.id+'>'+(this.options.content||"<span>无内容.</span>")+'</div>';
	this.init();
}
VFG.Popup.prototype.init = function() {
	let _this=this;
    layer.open({
    	id:this.id,
        title:this.options.name||false,
        type: this.options.type||1,
        shade:  this.options.shade||0,  
        resize :false,
        closeBtn: 0,
        skin:'layui-layer  layui-layer-city',
	    content: this.html,
	    success: function (layero, dIndex) {
	    	layui.$(layero).children('.layui-layer-content').css('overflow', 'visible');
	    	_this.dIndex=dIndex;
	    	_this.layero=layero;
			_this.width=(layui.$(_this.layero).css('width').replace('px','')*1)/2;
			_this.height=(layui.$(_this.layero).css('height').replace('px','')*1)+16;
			_this.setScreenPositon();
	    	_this.event=function(){
	    		_this.setScreenPositon();
	    	}
	    	_this.viewer.scene.postRender.addEventListener(_this.event);
	    	if(_this.success){
	    		_this.success(layero, dIndex)
	    	}
		},
		end:function(){
	    	if(_this.end){
	    		_this.end(_this.id)
	    	}
	    	_this.destroy();
		}
    }); 
};

VFG.Popup.prototype.setScreenPositon=function(){
	let _this = this;
	var cartesian2=Cesium.SceneTransforms.wgs84ToWindowCoordinates(_this.viewer.scene, _this.cartesian3);
	if (Cesium.defined(cartesian2)){
		layer.style(_this.dIndex, {
			left:(cartesian2.x-_this.width)+'px',
			top:(cartesian2.y-_this.height)+'px'
		});
	}
}

VFG.Popup.prototype.update=function(param){
	let _this = this;
	if(param.content){
		$("#"+this.id).html(param.content);
		_this.width=(layui.$(_this.layero).css('width').replace('px','')*1)/2;
		_this.height=(layui.$(_this.layero).css('height').replace('px','')*1)+16;
	}
	if(param.position){
		_this.position=param.position;
		_this.cartesian3=VFG.Util.getLnLaToC3(_this.position);
		_this.setScreenPositon();
	}
}

VFG.Popup.prototype.on=function(type,callback){
	if('success'===type){
		this.success=callback;
	}
	if('end'===type){
		this.end=callback;
	}
}
VFG.Popup.prototype.destroy = function() {
	var _this = this;
	if(_this.event){
		_this.viewer.scene.postRender.removeEventListener(_this.event);
	}
	
	if(_this.dIndex){layer.close(_this.dIndex);}
	delete this.viewer,
	delete this.option,
	delete this.position,
	delete this.layerIndex;
	delete this.layero;
	delete this.width;
	delete this.height;
	return Cesium.destroyObject(this);
};;
///<jscompress sourcefile="Tip.js" />
VFG.Tip=function(viewer, options) {
	this.viewer = viewer;
	this.options = options;
	this.frameDiv=this.viewer.cesiumWidget.container;
	this.isInit=false;
	this.init();
}
VFG.Tip.prototype.init = function() {
	var _self = this;
    if (_self.isInit) { return; }
    
    var div = document.createElement('DIV');
    div.className = "vfg-draw-tooltip right";

    var arrow = document.createElement('DIV');
    arrow.className = "vfg-draw-tooltip-arrow";
    div.appendChild(arrow);

    var title = document.createElement('DIV');
    title.className = "vfg-draw-tooltip-inner";
    div.appendChild(title);
    
    this._div = div;
    this._title = title;
    _self.frameDiv.appendChild(div);
    _self.isInit = true;
};
VFG.Tip.prototype.setVisible = function(visible) {
	var _self = this;
    if (!_self.isInit) { return; }
    _self._div.style.display = visible ? 'block' : 'none';
};
VFG.Tip.prototype.showAt = function (position, message) {
	var _self = this;
    if (!_self.isInit) { return; }
    if (position && message) {
    	_self.setVisible(true);
    	_self._title.innerHTML = message;
    	_self._div.style.position = "absolute"
    	_self._div.style.left = position.x + 20 + "px";
    	_self._div.style.top = (position.y - this._div.clientHeight/2) + "px";
    }
};
VFG.Tip.prototype.destroy = function() {
	var _self = this;
	if( _self._div){
		$( _self._div).remove();
	}
	if( _self._title){
		$( _self._title).remove();
	}
	return Cesium.destroyObject(this);
};;
///<jscompress sourcefile="Viewer.js" />
function Viewer(option) {
  this.option = Cesium.defaultValue(option, Cesium.defaultValue.EMPTY_OBJECT);
  this.scene3DOnly = (option && option.scene3DOnly) ? option.scene3DOnly : true,
    this.selectionIndicator = (option && option.selectionIndicator) ? option.selectionIndicator : false,
    this.animation = (option && option.animation) ? option.animation : false,
    this.timeline = (option && option.timeline) ? option.timeline : false,
    this.navigationHelpButton = (option && option.navigationHelpButton) ? option.navigationHelpButton : false,
    this.fullscreenButton = (option && option.fullscreenButton) ? option.fullscreenButton : false,
    this.geocoder = (option && option.geocoder) ? option.geocoder : false,
    this.homeButton = (option && option.homeButton) ? option.homeButton : false,
    this.shouldAnimate = (option && option.shouldAnimate) ? option.shouldAnimate : false,
    this.sceneModePicker = (option && option.sceneModePicker) ? option.sceneModePicker : false,
    this.shouldAnimate = (option && option.shouldAnimate) ? option.shouldAnimate : true,
    this.infoBox = (option && option.infoBox) ? option.infoBox : false,
    this.requestRenderMode = (option && option.requestRenderMode) ? option.requestRenderMode : false,
    this.navigationInstructionsInitiallyVisible = (option && option.navigationInstructionsInitiallyVisible) ? option.navigationInstructionsInitiallyVisible :false,
    this.baseLayerPicker = (option && option.baseLayerPicker) ? option.baseLayerPicker : false,
    this.maximumRequests = (option && option.maximumRequests) ? option.maximumRequests : 50;
  this.maximumRequestsPerServer = (option && option.maximumRequestsPerServer) ? option.maximumRequestsPerServer : 6;
  this.throttleRequests = (option && option.throttleRequests) ? option.throttleRequests : true;
  this.defaultAccessToken = (option && option.defaultAccessToken) ? option.defaultAccessToken :'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJiZjliY2NhNS1iMThiLTQzZTYtOWM1ZS03NDMxMmY3YjIyNmUiLCJpZCI6MjAwNDcsInNjb3BlcyI6WyJhc2wiLCJhc3IiLCJhc3ciLCJnYyJdLCJpYXQiOjE1ODMxOTk3NTl9.lzdqsXU24bvovmmaRPXcD3jmSH0WmYTwmX6isCx8qfA';
  let _this = this;
  Cesium.RequestScheduler.maximumRequests = _this.maximumRequests;
  Cesium.RequestScheduler.maximumRequestsPerServer = _this.maximumRequestsPerServer;
  Cesium.RequestScheduler.throttleRequests = _this.throttleRequests;
  Cesium.throttleRequestByServer.maximumRequestsPerServer=1024;
  
  Cesium.Ion.defaultAccessToken = _this.defaultAccessToken;

  _this.viewer = new Cesium.Viewer(this.option.domId, {
    scene3DOnly: _this.scene3DOnly,
    selectionIndicator: _this.selectionIndicator,
    baseLayerPicker: _this.baseLayerPicker,
    animation: _this.animation,
    timeline: _this.timeline,
    navigationHelpButton: _this.navigationHelpButton,
    fullscreenButton: _this.fullscreenButton,
    geocoder: _this.geocoder,
    homeButton: _this.homeButton,
    shouldAnimate: _this.shouldAnimate,
    sceneModePicker: _this.sceneModePicker,
    shouldAnimate: _this.shouldAnimate,
    infoBox: _this.infoBox,
    requestRenderMode: _this.requestRenderMode,
    navigationInstructionsInitiallyVisible: _this.navigationInstructionsInitiallyVisible,
    baseLayerPicker: _this.baseLayerPicker,
    contextOptions: {
      webgl: {
        alpha: true,
        depth: true,
        stencil: true,
        antialias: true,
        premultipliedAlpha: true,
        preserveDrawingBuffer: true,
        failIfMajorPerformanceCaveat: true
      }
    },
/*    imageryProvider: new Cesium.WebMapTileServiceImageryProvider({
    	url: "http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=9762e665a084d0bed485e09ce57e2728",
        layer: "tdtBasicLayer",
        style: "default",
        format: "image/jpeg",
        tileMatrixSetID: "GoogleMapsCompatible",
        show: false
    })*/
  });
	this.viewer.scene.globe.depthTestAgainstTerrain = false;
	this.viewer.cesiumWidget.creditContainer.style.display = "none";

  //设置操作习惯(禁止中间滑轮调整视角)
	this.viewer.scene.screenSpaceCameraController.zoomEventTypes = [Cesium.CameraEventType.WHEEL, Cesium.CameraEventType.PINCH];
	this.viewer.scene.screenSpaceCameraController.tiltEventTypes = [Cesium.CameraEventType.PINCH, Cesium.CameraEventType.RIGHT_DRAG];

	//解决模糊问题
	if(Cesium.FeatureDetection.supportsImageRenderingPixelated()){//判断是否支持图像渲染像素化处理
		this.viewer.resolutionScale = window.devicePixelRatio;
	}
	//是否开启抗锯齿
	this.viewer.scene.fxaa = true;
	this.viewer.scene.postProcessStages.fxaa.enabled = true;

	// 去掉entity的点击事件 start
	this.viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
	this.viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
	this.viewer.scene.globe.baseColor = new Cesium.Color.fromCssColorString("#546a53"); //地表背景色
  return _this.viewer;
}
;
///<jscompress sourcefile="WebSocket.js" />
VFG.WebSocket = function(options) {
	this.ws;
	this.lockReconnect = false;
	this.options = options;
	this.url = options.ws;
	let _this=this;
	this.heartCheck = {
        timeout: 60000,
        timeoutObj: null,
        reset: function(){
            clearTimeout(this.timeoutObj);
            return this;
        },
        start: function(){
            this.timeoutObj = setTimeout(function(){
            	_this.ws.send("HeartBeat");
            }, this.timeout)
        }
    }
}

VFG.WebSocket.prototype.createWebSocket=function() {
	let _this=this;
    try {
    	_this.ws = new WebSocket(_this.url);
    	_this.initEventHandle();
    } catch (e) {
    	_this.reconnect();
    }     
}

VFG.WebSocket.prototype.initEventHandle=function() {
	let _this=this;
	_this.ws.onclose = function () {
		_this.reconnect();
    };
    _this. ws.onerror = function () {
    	_this.reconnect();
    };
    _this.ws.onopen = function () {
    	_this.heartCheck.reset().start();
    };
    _this.ws.onmessage = function (event) {
    	if('HeartBeat'!=event.data){
    		if(_this.options.callback){
    			_this.options.callback(event.data);
    		}
    	}
    	_this.heartCheck.reset().start();
    }
}

VFG.WebSocket.prototype.reconnect=function() {
	let _this=this;
    if(_this.lockReconnect) return;
    _this.lockReconnect = true;
    setTimeout(function () {
    	_this.createWebSocket();
    	_this.lockReconnect = false;
    }, 2000);
}

VFG.WebSocket.prototype.destroy = function() {
	var _self = this;
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="Render.js" />
VFG.Render = function() {
}
/**
 * 底图
 */
VFG.Render.getImageryProvider = function(viewer,options) {
	if('tianditu'==options.thing.provider){
		return new VFG.TiandituImageryProvider(viewer,options);
	}
	else if('custom'==options.thing.provider){
		return new VFG.CommonImageryProvider(viewer,options);
	}
}

VFG.Render.getTModel = function(viewer,options,uri) {
	if(options.thing && options.thing.isRelative=='1' && options.thing.url 
		&& options.thing.url.indexOf('https://')==-1 && options.thing.url.indexOf('http://')==-1){
		options.thing.url=uri+options.thing.url
	}
	return new VFG.TModel(viewer, options)
}

VFG.Render.getPModel = function(viewer,options,uri) {
	if(options.thing && options.thing.isRelative=='1' && options.thing.url 
		&& options.thing.url.indexOf('https://')==-1 && options.thing.url.indexOf('http://')==-1){
		options.thing.url=uri+options.thing.url
	}
	return new VFG.PModel(viewer,options);
}

VFG.Render.getVModel = function(viewer,options,uri) {
	if(options.thing && options.thing.isRelative=='1' && options.thing.url 
		&& options.thing.url.indexOf('https://')==-1 && options.thing.url.indexOf('http://')==-1){
		options.thing.url=uri+options.thing.url;
	}
	if(options.thing && options.thing.isRelative=='1' && options.thing.thumbnail 
		&& options.thing.thumbnail.indexOf('https://')==-1 && options.thing.thumbnail.indexOf('http://')==-1){
		options.thing.thumbnail=uri+options.thing.thumbnail;
	}
	if(options.thing && options.thing.videoRelative=='1' && options.thing.videoType=='0' && options.thing.videoUrl 
		&& options.thing.videoUrl.indexOf('https://')==-1 && options.thing.videoUrl.indexOf('http://')==-1){
		options.thing.videoUrl=uri+options.thing.videoUrl;
	}
	return new VFG.VModel(viewer,options);
}

VFG.Render.getERoadMark = function(viewer,options,uri) {
	if(options && options.thing && options.thing.coordinates && Object.prototype.toString.call(options.thing.coordinates) === "[object String]"){
		var coordinates = options.thing.coordinates;
		options.thing.coordinates=JSON.parse(coordinates);
	}
	return new VFG.ERoadMark(viewer,options);
}

VFG.Render.getPointMark = function(viewer,options,uri) {
	if(options && options.thing  && options.thing.image 
		&& options.thing.image.indexOf('https://')==-1 && options.thing.image.indexOf('http://')==-1){
		options.thing.image=uri+options.thing.image;
	}
	return new VFG.PPoint(viewer,options);
}

VFG.Render.getEPolyline = function(viewer,options,uri) {
	if(options && options.thing && options.thing.positions && Object.prototype.toString.call(options.thing.positions) === "[object String]"){
		var positions = options.thing.positions;
		options.thing.positions=JSON.parse(positions);
	}
	return new VFG.EPolyline(viewer,options);
}



;
///<jscompress sourcefile="Util.js" />
VFG.Util = function() {
}
VFG.Util.ECE=new Cesium.ECEF();
VFG.Util.getUuid = function() {
	var s = [];
	var hexDigits = "0123456789abcdef";
	for (var i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4";
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
	s[8] = s[13] = s[18] = s[23] = "-";
	var uuid = s.join("");
	return uuid;
}
/**
* 校验只要是数字（包含正负整数，0以及正负浮点数）就返回true
**/

VFG.Util.isNumber=function(val){
    return typeof value === 'number' && !isNaN(value);
}

VFG.Util.getVisualAngle = function(viewer) {
	return {
		heading : Cesium.Math.toDegrees(viewer.camera.heading).toFixed(2),
		pitch : Cesium.Math.toDegrees(viewer.camera.pitch).toFixed(2),
		roll :  Cesium.Math.toDegrees(viewer.camera.roll).toFixed(2),
		position : this.getLnLaFormC3(viewer, viewer.camera.position)
	}
}

VFG.Util.getLnLaFormC3 = function(viewer, cartesian3) {
	var ellipsoid = viewer.scene.globe.ellipsoid;
	var cartographic = ellipsoid.cartesianToCartographic(cartesian3);
	var lat = Cesium.Math.toDegrees(cartographic.latitude).toFixed(7);
	var lng = Cesium.Math.toDegrees(cartographic.longitude).toFixed(7);
	var alt = cartographic.height.toFixed(2);
	return {
		x : lng,
		y : lat,
		z : alt
	};
}


VFG.Util.getScreenToC3 =function(viewer, position, noPickEntity) {
	
	var scene=viewer.scene;
	
    var cartesian;

    //在模型上提取坐标   
    var pickedObject;
    try {
        pickedObject = scene.pick(position, 5, 5);
    } catch (e) {
        console.log("scene.pick 拾取位置时异常");
    }

    if (scene.pickPositionSupported && Cesium.defined(pickedObject)) {
        var pcEntity = this.hasPickedModel(pickedObject, noPickEntity);
        if (!pcEntity) {
            cartesian = scene.pickPosition(position);
            if (Cesium.defined(cartesian)) {
                var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
                if (cartographic.height >= 0) return cartesian;
                if (!Cesium.defined(pickedObject.id) && cartographic.height >= -500) return cartesian;
            } else {
            }
        } else {
        	//cartesian = this.getScreenToC3(viewer, position, noPickEntity);
        }
    } else {}

    //onlyPickModelPosition是在 ViewerEx 中定义的对外属性
    //通过 viewer.mars.onlyPickModelPosition 进行修改
    if (scene.onlyPickModelPosition) return cartesian; //只取模型上的时候，不继续读取了


    //测试scene.pickPosition和globe.pick的适用场景 https://zhuanlan.zhihu.com/p/44767866
    //1. globe.pick的结果相对稳定准确，不论地形深度检测开启与否，不论加载的是默认地形还是别的地形数据；
    //2. scene.pickPosition只有在开启地形深度检测，且不使用默认地形时是准确的。
    //注意点： 1. globe.pick只能求交地形； 2. scene.pickPosition不仅可以求交地形，还可以求交除地形以外其他所有写深度的物体。

    //提取鼠标点的地理坐标 
    if (scene.mode === Cesium.SceneMode.SCENE3D) {
        //三维模式下
        var pickRay = scene.camera.getPickRay(position);
        cartesian = scene.globe.pick(pickRay, scene);
    } else {
        //二维模式下
        cartesian = scene.camera.pickEllipsoid(position, scene.globe.ellipsoid);
    }

    if (Cesium.defined(cartesian) && scene.camera.positionCartographic.height < 10000) {
        var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        // console.log(cartographic.height);
        if (cartographic.height < -5000) return null; //屏蔽无效值
    }

    return cartesian;
}


/**
 * 屏幕坐标转世界坐标
 */
/*VFG.Util.getScreenToC3 = function(viewer, position, noPickEntity) {
	var scene = viewer.scene;
	var cartesian3;
	if (scene.mode !== Cesium.SceneMode.MORPHING) {
		var pickedObject = scene.pick(position);
		if (scene.pickPositionSupported && Cesium.defined(pickedObject)) {
			if (!this.hasPickedModel(pickedObject, noPickEntity)) {
				cartesian3 = viewer.scene.pickPosition(position);
				if (Cesium.defined(cartesian3)) {
					var height = Cesium.Cartographic.fromCartesian(cartesian3).height;
					var lat = Cesium.Math.toDegrees(Cesium.Cartographic
							.fromCartesian(cartesian3).latitude);
					var lng = Cesium.Math.toDegrees(Cesium.Cartographic
							.fromCartesian(cartesian3).longitude);
					return viewer.scene.clampToHeight(cartesian3);
				}
			}
		}
	}

	// 获取地形表面的经纬度高程坐标：
	if (!Cesium.defined(cartesian3) && (viewer.scene)) {
		var ray = viewer.camera.getPickRay(position);
		if (Cesium.defined(ray)) {
			cartesian3 = viewer.scene.globe.pick(ray, viewer.scene);
			if (Cesium.defined(cartesian3)) {
				var height = Cesium.Cartographic.fromCartesian(cartesian3).height;
				var lat = Cesium.Math.toDegrees(Cesium.Cartographic
						.fromCartesian(cartesian3).latitude);
				var lng = Cesium.Math.toDegrees(Cesium.Cartographic
						.fromCartesian(cartesian3).longitude);
				return Cesium.Cartesian3.fromDegrees(lng, lat,
						height > 0 ? height : 0);
			}
		}

	}

	// 二维坐标，获取椭球体表面的经纬度坐标：
	if (!Cesium.defined(cartesian3)) {
		cartesian3 = viewer.scene.camera.pickEllipsoid(position,
				viewer.scene.globe.ellipsoid);
		return cartesian3;
	}
	return cartesian3;
}*/

VFG.Util.hasPickedModel = function(pickedObject, noPickEntity) {
	if( Cesium.defined(pickedObject) && Cesium.defined(noPickEntity)){
		if(Cesium.defined(noPickEntity.id) && Cesium.defined(pickedObject.id)){
			if(Cesium.defined(noPickEntity.id.id) && Cesium.defined(pickedObject.id.id) && noPickEntity.id.id==pickedObject.id.id){
				return true
			}
			else if(noPickEntity.id==pickedObject.id){
				return true
			}
		}
	}
	return false;
}

VFG.Util.getScreenToLnLa = function(viewer, position, noPickEntity) {
	let cartesian3 = VFG.Util.getScreenToC3(viewer, position, noPickEntity);
	if (!Cesium.defined(cartesian3)) {
		return;
	}

	let LnLa = VFG.Util.getLnLaFormC3(viewer, cartesian3);
	if (Cesium.defined(LnLa)) {
		return LnLa;
	}
};

VFG.Util.getLnLaToC3 = function(position) {
	return  Cesium.Cartesian3.fromDegrees(position.x*1, position.y*1,position.z*1);
};

VFG.Util.getC3ToLnLa = function(viewer,cartesian3) {
	var ellipsoid=viewer.scene.globe.ellipsoid;
	var cartographic=ellipsoid.cartesianToCartographic(cartesian3);
	var lat=Cesium.Math.toDegrees(cartographic.latitude).toFixed(7);
	var lng=Cesium.Math.toDegrees(cartographic.longitude).toFixed(7);
	var alt=cartographic.height.toFixed(2);
	return {
		x:lng,
		y:lat,
		z:alt
	};
}

/**
 * viewer:viewer cameraPosition:起点 position:目标
 */
VFG.Util.getHeadingPitchRoll = function(viewer,cameraPosition, position) {
    var e = cameraPosition,
    t = position,
    i = Cesium.Cartesian3.normalize(Cesium.Cartesian3.subtract(t, e, new Cesium.Cartesian3), new Cesium.Cartesian3),
    a = Cesium.Cartesian3.normalize(e, new Cesium.Cartesian3),
    n = new Cesium.Camera(viewer.scene);
    n.position = e,
    n.direction = i,
    n.up = a,
    i = n.directionWC,
    a = n.upWC;
    var r = n.rightWC,
    o = new Cesium.Cartesian3,
    l = new Cesium.Matrix3,
    u = new Cesium.Quaternion;
    r = Cesium.Cartesian3.negate(r, o);
    var d = l;
    Cesium.Matrix3.setColumn(d, 0, r, d),
    Cesium.Matrix3.setColumn(d, 1, a, d),
    Cesium.Matrix3.setColumn(d, 2, i, d);
    var c = Cesium.Quaternion.fromRotationMatrix(d, u);
    var hpr = Cesium.HeadingPitchRoll.fromQuaternion(c);
	var heading = Cesium.Math.toDegrees(hpr.heading).toFixed(2);
	var pitch = Cesium.Math.toDegrees(hpr.pitch).toFixed(2);
	var roll = Cesium.Math.toDegrees(hpr.roll).toFixed(2);
	return hpr;
/*	return {
		heading:heading,
		pitch:pitch,
		roll:roll,
	}*/
	
};

VFG.Util.getDistance = function(satrt, end) {
	var geodesic = new Cesium.EllipsoidGeodesic();
	geodesic.setEndPoints(satrt, end);
	var distance = geodesic.surfaceDistance
	return distance;
}

//空间两点距离计算函数
VFG.Util.getSpaceDistance=function(position1,position2){
	var distance = 0;
    var point1cartographic = Cesium.Cartographic.fromCartesian(VFG.Util.getLnLaToC3(position1));
    var point2cartographic = Cesium.Cartographic.fromCartesian(VFG.Util.getLnLaToC3(position2));
    /** 根据经纬度计算出距离* */
    var geodesic = new Cesium.EllipsoidGeodesic();
    geodesic.setEndPoints(point1cartographic, point2cartographic);
    var s = geodesic.surfaceDistance;
    // 返回两点之间的距离
    s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic.height, 2));
    distance = distance + s;
    return distance.toFixed(2);
}

/**
 * 飞行
 * {
 *  destination：{
 * 		x:0,
 * 		y:0,
 * 		z:0
 * },
 * 	orientation:{
 * 		heading"0,
 * 		pitch:0,
 * 		roll:0,
 * 	}
 * }
 */
VFG.Util.flyTo = function(viewer, option) {
	viewer.camera
			.flyTo({
				destination : Cesium.Cartesian3.fromDegrees(option.position.x,
						option.position.y, option.position.z),
				orientation : {
					heading : Cesium.Math
							.toRadians(option.orientation
									&& option.orientation.heading ? option.orientation.heading
									: 0),
					pitch : Cesium.Math
							.toRadians(option.orientation
									&& option.orientation.pitch ? option.orientation.pitch
									: 0),
					roll : Cesium.Math
							.toRadians(option.orientation
									&& option.orientation.roll ? option.orientation.roll
									: 0),
				}
			});
}

VFG.Util.getDistanceDisplayCondition = function(x,y) {
	var _this=this;
	if(Cesium.defined(x) && Cesium.defined(y) ){
		return new Cesium.DistanceDisplayCondition(x*1,y*1)
	}
	return null;
};

/**

 * 在坐标基础海拔上增加指定的海拔高度值

 * @param {Array} positions Cartesian3类型的数组

 * @param {Number} height 高度值

 * @return {Array} Cartesian3类型的数组

 */
VFG.Util.addPositionsHeight=function(positions, addHeight) {
    addHeight = Number(addHeight) || 0;
    if (isNaN(addHeight) || addHeight == 0) return positions;
    if (positions instanceof Array) {
        var arr = [];
        for (var i = 0, len = positions.length; i < len; i++) {
            var car = Cesium.Cartographic.fromCartesian(positions[i]);
            var point = Cesium.Cartesian3.fromRadians(car.longitude, car.latitude, car.height + addHeight);
            arr.push(point);
        }
        return arr;
    } else {
        var car = Cesium.Cartographic.fromCartesian(positions);
        return Cesium.Cartesian3.fromRadians(car.longitude, car.latitude, car.height + addHeight);
    }
}

VFG.Util.pick=function(viewer,position){
	if(Cesium.defined(viewer) && Cesium.defined(position)){
		let obj=viewer.scene.pick(position);
		if(Cesium.defined(obj)){
			if(Cesium.defined(obj.id) && (obj.id instanceof Cesium.Entity)){
				return obj;
			}
			else if(Cesium.defined(obj.primitive) && (obj.primitive instanceof Cesium.Billboard) && Cesium.defined(obj.id)){
				return obj;
			}
			else if(Cesium.defined(obj.primitive) && (obj.primitive instanceof Cesium.Label) && Cesium.defined(obj.id)){
				return obj;
			}
			else if(Cesium.defined(obj.primitive) && (obj.primitive instanceof Cesium.Primitive) && Cesium.defined(obj.id)){
				return obj;
			}
			else if (obj instanceof Cesium.Cesium3DTileFeature){
/*		        var propertyNames = obj.getPropertyNames();
		        var length = propertyNames.length;
		        for (var i = 0; i < length; ++i) {
		            var propertyName = propertyNames[i];
		            console.log(propertyName + ': ' + obj.getProperty(propertyName));
		        }*/
		        //obj.show=false;
		        return obj;
			}
			else{
				return obj;
			}
		}
	}
	return null;
}

VFG.Util.exportToImg=function(viewer,width,height){
	let canvas = viewer.scene.canvas;
	var imageWidth = width?width:800;
	let image = Canvas2Image.convertToImage(canvas, width, height,'png');
    return image.src;
}

VFG.Util.formatNum=function(num,digits){
	 return Number(Number(num).toFixed(digits || 0));
}

VFG.Util.package=function(viewer,option){
	if('rectangular'===option.type){
		return new VFG.Sensor(viewer,option);
	}
	else if('GLB'===option.type || 'GLTF'===option.type){
		return new VFG.PModel(viewer,option);
	}
}

VFG.Util.getTargetPosition=function(position,option){
	let TargetPosition=VFG.Util.ECE.enu_to_ecef({ 
		longitude:position.x*1, 
		latitude:position.y*1, 
		altitude:position.z*1
	},
	{ 
		distance: option.far*1, 
		azimuth:option.heading*1, 
		elevation:option.pitch*1
	});
	if(TargetPosition){
		return {
			x:TargetPosition.longitude,
			y:TargetPosition.latitude,
			z:TargetPosition.altitude,
		}
	}
}

VFG.Util.getHeading=function(position1, position2){
	let pointA=Cesium.Cartesian3.fromDegrees(position1.x*1, position1.y*1,position1.z*1)
	let pointB=Cesium.Cartesian3.fromDegrees(position2.x*1, position2.y*1,position2.z*1)
    let transform = Cesium.Transforms.eastNorthUpToFixedFrame(pointA);
	let positionvector = Cesium.Cartesian3.subtract(pointB, pointA, new Cesium.Cartesian3());
	let vector = Cesium.Matrix4.multiplyByPointAsVector(Cesium.Matrix4.inverse(transform, new Cesium.Matrix4()), positionvector, new Cesium.Cartesian3());
	let direction = Cesium.Cartesian3.normalize(vector, new Cesium.Cartesian3());
	let heading = Math.atan2(direction.y, direction.x) - Cesium.Math.PI_OVER_TWO;
    return Cesium.Math.TWO_PI - Cesium.Math.zeroToTwoPi(heading);
}

VFG.Util.getPitch=function(position1, position2){
	let pointA=Cesium.Cartesian3.fromDegrees(position1.x*1, position1.y*1,position1.z*1)
	let pointB=Cesium.Cartesian3.fromDegrees(position2.x*1, position2.y*1,position2.z*1)
    let transfrom = Cesium.Transforms.eastNorthUpToFixedFrame(pointA);
    const vector = Cesium.Cartesian3.subtract(pointB, pointA, new Cesium.Cartesian3());
    let direction = Cesium.Matrix4.multiplyByPointAsVector(Cesium.Matrix4.inverse(transfrom, transfrom), vector, vector);
    Cesium.Cartesian3.normalize(direction, direction);
    return Cesium.Math.PI_OVER_TWO - Cesium.Math.acosClamped(direction.z);
}

VFG.Util.getAngle=function(a,b,c){
	let p1=Cesium.Cartesian3.fromDegrees(a.x*1, a.y*1,a.z*1)
	let p2=Cesium.Cartesian3.fromDegrees(b.x*1, b.y*1,b.z*1)
	let p3=Cesium.Cartesian3.fromDegrees(c.x*1, c.y*1,c.z*1)
	var c1 = Cesium.Cartesian3.subtract(p2, p1, new Cesium.Cartesian3());
	var c2 = Cesium.Cartesian3.subtract(p3, p1, new Cesium.Cartesian3());
	var angle = Cesium.Cartesian3.angleBetween(c1, c2);
	return angle;
}

//获取模型的中心点信息
VFG.Util.getCenterForModel=function(tileset, transform) {
    var result = {};
    //记录模型原始的中心点
    var boundingSphere = tileset.boundingSphere;
    var position = boundingSphere.center;
    var catographic = Cesium.Cartographic.fromCartesian(position);

    var height = Number(catographic.height.toFixed(2));
    var longitude = Number(Cesium.Math.toDegrees(catographic.longitude).toFixed(6));
    var latitude = Number(Cesium.Math.toDegrees(catographic.latitude).toFixed(6));
    result = { x: longitude, y: latitude, z: height };

    //console.log("模型内部原始位置:" + JSON.stringify(result));

    //如果tileset自带世界矩阵矩阵，那么计算放置的经纬度和heading
    if (transform) {
        var matrix = Cesium.Matrix4.fromArray(tileset._root.transform);
        var pos = Cesium.Matrix4.getTranslation(matrix, new Cesium.Cartesian3());
        var wpos = Cesium.Cartographic.fromCartesian(pos);
        if (Cesium.defined(wpos)) {
            result.x = Number(Cesium.Math.toDegrees(wpos.longitude).toFixed(6));
            result.y = Number(Cesium.Math.toDegrees(wpos.latitude).toFixed(6));
            result.z = Number(wpos.height.toFixed(2));

            //取旋转矩阵
            var rotmat = Cesium.Matrix4.getMatrix3(matrix, new Cesium.Matrix3());
            //默认的旋转矩阵
            var defrotmat = Cesium.Matrix4.getMatrix3(Cesium.Transforms.eastNorthUpToFixedFrame(pos), new Cesium.Matrix3());

            //计算rotmat 的x轴，在defrotmat 上 旋转
            var xaxis = Cesium.Matrix3.getColumn(defrotmat, 0, new Cesium.Cartesian3());
            var yaxis = Cesium.Matrix3.getColumn(defrotmat, 1, new Cesium.Cartesian3());
            var zaxis = Cesium.Matrix3.getColumn(defrotmat, 2, new Cesium.Cartesian3());

            var dir = Cesium.Matrix3.getColumn(rotmat, 0, new Cesium.Cartesian3());

            dir = Cesium.Cartesian3.cross(dir, zaxis, dir);
            dir = Cesium.Cartesian3.cross(zaxis, dir, dir);
            dir = Cesium.Cartesian3.normalize(dir, dir);

            var heading = Cesium.Cartesian3.angleBetween(xaxis, dir);

            var ay = Cesium.Cartesian3.angleBetween(yaxis, dir);

            if (ay > Math.PI * 0.5) {
                heading = 2 * Math.PI - heading;
            }
            result.rotation_x = 0;
            result.rotation_y = 0;
            result.rotation_z = Number(Cesium.Math.toDegrees(heading).toFixed(1));

            result.heading = result.rotation_z; //兼容v1老版本

           // console.log("模型内部世界矩阵:" + JSON.stringify(result));
        }
    }

    return result;
}

VFG.Util.addPositionHeight=function(cartesian, height) {
    var carto = Cesium.Cartographic.fromCartesian(cartesian);
    if (height != 0) {
        var positionNew = Cesium.Cartesian3.fromRadians(carto.longitude, carto.latitude, carto.height+height);
        return positionNew;
    }
    return cartesian;
}

VFG.Util.formatNum=function(num, digits) {
    return Number(Number(num).toFixed(digits || 0));
}
;
///<jscompress sourcefile="EModel.js" />
VFG.EModel=function(viewer, options) {
	this.viewer = viewer;
	this.options = options;
	this.parentId= options.parentId||'';
	this.id= options.id;
	this.name= options.name||'';
	this.code= options.code||'';
	this.type= options.type||'';
	this.position=options.position||null;
	this.orientation=options.orientation||{};
	this.model=options.model||{};
	this.attribute=options.attribute||{};
	this.propertys=options.propertys||[];
	this.antennaMap=new Map();
	this.init();
}
VFG.EModel.prototype.init = function() {
	let _this=this;
	var param={
			id: this.id,
			name :this.name,
			url :this.model.url||'',
			modelMatrix : this.getModelMatrix(),
			scale :this.model.scale*1||1,
			show : this.model.show||true,   
			minimumPixelSize:this.model.minimumPixelSize||0,
			allowPicking : this.model.allowPicking||true,        
			debugShowBoundingVolume : this.model.debugShowBoundingVolume||false, 
			debugWireframe : this.model.debugWireframe||false, 
			backFaceCulling:this.model.backFaceCulling||false, 
			shadows: this.model.shadows||false,   
	}
	if('1'== this.model.distanceDisplayCondition){
		param.distanceDisplayCondition=VFG.Util.getDistanceDisplayCondition( this.model.distanceNear, this.model.distanceFar);	
	}
	if('1'== this.model.silhouette){
		param.silhouetteColor= this.model.silhouetteColor? Cesium.Color.fromCssColorString( this.model.silhouetteColor):Cesium.Color.BLACK;	
		param.silhouetteSize= this.model.silhouetteSize*1||0;	
	}
	if('1'== this.model.fill){
		param.color= this.model.fillColor? Cesium.Color.fromCssColorString( this.model.fillColor):Cesium.Color.BLACK;	
	}
	this.primity = this.viewer.scene.primitives.add(Cesium.Model.fromGltf(param));
	this.primity.readyPromise.then(function(model) {
		if(_this.success){
			_this.success(model)
		}
	}).otherwise(function(error){
		if(_this.error){
			_this.error(error);
		}
    });
	if(_this.options.antennas){
		for(var p in _this.options.antennas){
			_this.addAntenna(_this.options.antennas[p]);
		}
	}
};
VFG.EModel.prototype.getModelMatrix=function(){
    var hpRoll = new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(this.orientation.heading || 0), Cesium.Math.toRadians(this.orientation.pitch || 0), Cesium.Math.toRadians(this.orientation.roll || 0));
    var fixedFrameTransform = Cesium.Transforms.eastNorthUpToFixedFrame;
    let cartesian3=Cesium.Cartesian3.fromDegrees(this.position.x*1, this.position.y*1,this.position.z*1);
    var modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(cartesian3, hpRoll, this.viewer.scene.globe.ellipsoid, fixedFrameTransform);
    return modelMatrix;
}

VFG.EModel.prototype.getRadius=function(){
    return this.primity.boundingSphere.radius;
}


VFG.EModel.prototype.on=function(type,callback){
	if('success'==type){
		this.success=callback;
	}
	if('error'==type){
		this.error=callback;
	}
}

VFG.EModel.prototype.update=function(param){

	if(param.position){
		this.position=param.position;
	}
	
	if(param.orientation){
		if(this.orientation.pitch){
			this.orientation.pitch=param.orientation.pitch;
		}
		if(this.orientation.heading){
			this.orientation.heading=param.orientation.heading;
		}
		if(this.orientation.roll){
			this.orientation.roll=param.orientation.roll;
		}
	}
	
	if(this.primity){
		this.primity.modelMatrix=this.getModelMatrix();
	}
	this.updateAntennas();
}

VFG.EModel.prototype.updatePosition=function(position){
	this.position=position;
	if(this.primity){
		this.primity.modelMatrix=this.getModelMatrix();
		this.updateAntennas();
	}
}

VFG.EModel.prototype.updateAttribute=function(attribute){
	this.attribute=attribute;
	if(attribute && attribute.name){
		this.name=attribute.name;
		this.attribute.name=attribute.name;
	}
	if(attribute && attribute.parentId){
		this.parentId=attribute.parentId;
		this.attribute.parentId=attribute.parentId;
	}
	
	if(attribute && attribute.code){
		this.attribute.code=attribute.code;
		this.code=attribute.code;
	}
	if(attribute && attribute.sort){
		this.attribute.sort=attribute.sort;
	}
}

/**
 * 缩放
 */
VFG.EModel.prototype.updateScale=function(scale){
	this.model.scale=scale;
	if(this.primity){
		this.primity.scale=this.model.scale*1;
	}
}

VFG.EModel.prototype.updateHeading=function(heading){
	this.orientation.heading=heading;
	if(this.primity){
		this.primity.modelMatrix=this.getModelMatrix();
		this.updateAntennas();
	}
}

VFG.EModel.prototype.updatePitch=function(pitch){
	this.orientation.pitch=pitch;
	if(this.primity){
		this.primity.modelMatrix=this.getModelMatrix();
		this.updateAntennas();
	}
}

VFG.EModel.prototype.updateRoll=function(roll){
	this.orientation.roll=roll;
	if(this.primity){
		this.primity.modelMatrix=this.getModelMatrix();
		this.updateAntennas();
	}
}

VFG.EModel.prototype.updateMinimumPixelSize=function(minimumPixelSize){
	this.model.minimumPixelSize=minimumPixelSize;
	if(this.primity){
		this.primity.minimumPixelSize=minimumPixelSize;
	}
}

VFG.EModel.prototype.updateColor=function(color){
	this.model.fillColor=color;
	if(this.primity){
		this.primity.color=color? Cesium.Color.fromCssColorString(color):Cesium.Color.WHITE;	
	}
}

VFG.EModel.prototype.updateSilhouetteColor=function(silhouetteColor){
	this.model.silhouetteColor=silhouetteColor;
	if(this.primity){
		this.primity.silhouetteColor=silhouetteColor? Cesium.Color.fromCssColorString(silhouetteColor):Cesium.Color.WHITE;	
	}
}
VFG.EModel.prototype.updateSilhouetteSize=function(silhouetteSize){
	this.model.silhouetteSize=silhouetteSize;
	if(this.primity){
		this.primity.silhouetteSize=silhouetteSize*1;	
	}
}

VFG.EModel.prototype.updateDistanceDisplay=function(display){
	if(display.distanceNear){
		this.model.distanceNear=display.distanceNear;
	}
	if(display.distanceFar){
		this.model.distanceFar=display.distanceFar;
	}
	if(this.primity){
		this.primity.distanceDisplayCondition=VFG.Util.getDistanceDisplayCondition(this.model.distanceNear||0,this.model.distanceFar||5000);	
	}
}

VFG.EModel.prototype.isDistanceDisplay=function(display){
	this.model.distanceDisplayCondition=display;
	if(this.primity){
		if('1'===display){
			this.primity.distanceDisplayCondition=VFG.Util.getDistanceDisplayCondition(this.model.distanceNear||0,this.model.distanceFar||5000);	
		}else{
			this.primity.distanceDisplayCondition=null;	
		}
	}
}

VFG.EModel.prototype.isSilhouette=function(silhouette){
	this.model.silhouette=silhouette;
	if(this.primity){
		if('1'===silhouette){
			this.primity.silhouetteColor= this.model.silhouetteColor? Cesium.Color.fromCssColorString( this.model.silhouetteColor):Cesium.Color.WHITE;	
			this.primity.silhouetteSize= this.model.silhouetteSize*1||0;	
		}else{
			this.primity.silhouetteColor= Cesium.Color.WHITE;	
			this.primity.silhouetteSize= 0;	
		}
	}
}

VFG.EModel.prototype.isFill=function(fill){
	this.model.fill=fill;
	if(this.primity){
		if('1'===fill){
			this.primity.color= this.model.fillColor? Cesium.Color.fromCssColorString( this.model.fillColor):Cesium.Color.WHITE;	
		}else{
			this.primity.color= Cesium.Color.WHITE;	
		}
	}
}

VFG.EModel.prototype.isShadows=function(shadows){
	this.model.shadows=shadows;
	if(this.primity){
		if('1'===shadows){
			this.primity.shadows= this.model.shadows*1;	
		}else{
			this.primity.shadows= this.model.shadows*1;	
		}
	}
}

VFG.EModel.prototype.selected=function(){
	if(this.primity){
		this.primity.silhouetteColor= Cesium.Color.YELLOW;	
		this.primity.silhouetteSize= 2;	
	}
}

VFG.EModel.prototype.unselected=function(){
	if(this.primity){
		this.primity.silhouetteColor= this.model.silhouetteColor? Cesium.Color.fromCssColorString( this.model.silhouetteColor):Cesium.Color.WHITE;	
		this.primity.silhouetteSize= 0;	
	}
}

VFG.EModel.prototype.isAnimation=function(animation){
	this.model.animation=animation;
	if(this.primity){
		if('1'===animation){
			this.primity.animation= this.model.animation*1;	
		}else{
			this.primity.animation= this.model.animation*1;	
		}
	}
}

VFG.EModel.prototype.updateProperty= function(property) {
	var _this = this;
	if(_this.propertys){
		for(let index in _this.propertys){
			if(property.id==_this.propertys[index].id){
				_this.propertys.splice(index,1,property);
				return;
			}
		}
		_this.propertys.push(property);
	}
};

VFG.EModel.prototype.removeProperty= function(id) {
	var _this = this;
	if(_this.propertys){
		for(let index in _this.propertys){
			if(id==_this.propertys[index].id){
				_this.propertys.splice(index,1);
				return;
			}
		}
	}
};

VFG.EModel.prototype.addAntenna= function(param) {
	var _this = this;
	if(!_this.antennaMap.has(param.id)){
		_this.createAntenna(param);
	}else{
		this.updateAntenna(param)
	}
};

VFG.EModel.prototype.createAntenna= function(param) {
	var _this = this;
	let heading;
	if('0'==param.position){
		heading=(this.orientation.heading||0)*1+90;
	}
	else if('1'==param.position){
		heading=(this.orientation.heading||0)*1+270;
	}
	else if('2'==param.position){
		heading=(this.orientation.heading||0)*1+180;
	}
	else if('3'==param.position){
		heading=(this.orientation.heading||0)*1+0;
	}
	let tartPosition=VFG.Util.getTargetPosition({
		x:_this.position.x*1,
		y:_this.position.y*1,
		z:_this.position.z*1+(param.relativeHeight*1)
	},{
		far:param.relativeFar*1,//距离
		heading:heading*1,
		pitch:0,
	});
	if(tartPosition && tartPosition.x && tartPosition.y){
		let antenna = this.viewer.entities.add({
		  id: param.id,
		  name: param.name||'',
		  position: Cesium.Cartesian3.fromDegrees(tartPosition.x*1,tartPosition.y*1, tartPosition.z*1),
	      point: new Cesium.PointGraphics({
	          color: Cesium.Color.SKYBLUE,
	          pixelSize: param.pixelSize||5,
	          outlineColor: Cesium.Color.YELLOW,
	          outlineWidth: 3,
	      }),
		})
		_this.antennaMap.set(param.id,param)	
	}
};

VFG.EModel.prototype.updateAntenna= function(param) {
	var _this = this;
	if(_this.antennaMap.has(param.id)){
		if(param.name){
			_this.antennaMap.get(param.id).name=param.name
		}
		if(param.code){
			_this.antennaMap.get(param.id).code=param.code
		}
		if(param.relativeHeight){
			_this.antennaMap.get(param.id).relativeHeight=param.relativeHeight
		}
		if(param.position){
			_this.antennaMap.get(param.id).position=param.position
		}
/*		if(param.relativePitch){
			_this.antennaMap.get(param.id).relativePitch=param.relativePitch
		}*/
		if(param.relativeFar){
			_this.antennaMap.get(param.id).relativeFar=param.relativeFar
		}
		if(param.pixelSize){
			_this.antennaMap.get(param.id).pixelSize=param.pixelSize
		}
		if(param.heading){
			_this.antennaMap.get(param.id).heading=param.heading
		}
		if(param.pitch){
			_this.antennaMap.get(param.id).pitch=param.pitch
		}
		if(param.roll){
			_this.antennaMap.get(param.id).roll=param.roll
		}
		let antenna=_this.viewer.entities.getById(param.id);
		if(antenna){
			let heading;
			if('0'==param.position){
				heading=(this.orientation.heading||0)*1+90;
			}
			else if('1'==param.position){
				heading=(this.orientation.heading||0)*1+270;
			}
			else if('2'==param.position){
				heading=(this.orientation.heading||0)*1+180;
			}
			else if('3'==param.position){
				heading=(this.orientation.heading||0)*1+0;
			}
			
			let tartPosition=VFG.Util.getTargetPosition({
				x:_this.position.x*1,
				y:_this.position.y*1,
				z:_this.position.z*1+(param.relativeHeight*1)
			},{
				far:param.relativeFar*1,//距离
				heading:heading*1,
				pitch:0,
			});
			
			let h=VFG.Util.getHeading({
				x:_this.position.x*1,y: _this.position.y*1,z:tartPosition.z*1
			},tartPosition);
			let p=VFG.Util.getPitch({
				x:_this.position.x*1,y: _this.position.y*1,z:tartPosition.z*1
			},tartPosition);
			
			let d=VFG.Util.getSpaceDistance({
				x:_this.position.x*1,y: _this.position.y*1,z:tartPosition.z*1
			},tartPosition)
			
			 tartPosition=VFG.Util.getTargetPosition({
				x:_this.position.x*1,
				y:_this.position.y*1,
				z:_this.position.z*1+(param.relativeHeight*1)
			},{
				far:d,//距离
				heading:h*1,
				pitch:p*1+((_this.orientation.roll||0)*1),
			});
			
			console.log(tartPosition);
		//	tartPosition=_this.getRollPosition(tartPosition,(_this.orientation.roll||0)*1)
			
			
			if(tartPosition && tartPosition.x && tartPosition.y){
				antenna.name=_this.antennaMap.get(param.id).name;
				antenna.position=Cesium.Cartesian3.fromDegrees(tartPosition.x*1, tartPosition.y*1,tartPosition.z*1);
			}
		}
	}
};

VFG.EModel.prototype.removeAntenna= function(id) {
	var _this = this;
	if(_this.antennaMap.has(id)){
		_this.viewer.entities.removeById(id);
		_this.antennaMap.delete(id)
	}
};

VFG.EModel.prototype.updateAntennas= function() {
	var _this = this;
	if(this.antennaMap){
		_this.antennaMap.forEach(function (value,key){
			try{
				_this.updateAntenna(value);
			}catch (e) {
			}finally{
			}
		});
	}
};


VFG.EModel.prototype.getRollPosition=function(a,roll){
	console.log(a,roll);
	let A=Cesium.Cartesian3.fromDegrees(a.x*1, a.y*1,a.z*1)
	let B=Cesium.Cartesian3.fromDegrees(this.position.x*1, this.position.y*1,a.z*1)
	
	// 计算B的地面法向量
	var chicB = Cesium.Cartographic.fromCartesian(B);
	chicB.height = 0;
	var dB = Cesium.Cartographic.toCartesian(chicB);
	var normaB = Cesium.Cartesian3.normalize(Cesium.Cartesian3.subtract(dB, B, new Cesium.Cartesian3()), new Cesium.Cartesian3())
	// 构造基于B的法向量旋转90度的矩阵
	var Q = Cesium.Quaternion.fromAxisAngle(normaB, Cesium.Math.toRadians(roll));
	var m3 = Cesium.Matrix3.fromQuaternion(Q);
	var m4 = Cesium.Matrix4.fromRotationTranslation(m3);
	
	// 计算A点相对B点的坐标A1
	var A1 = Cesium.Cartesian3.subtract(A, B, new Cesium.Cartesian3());
	//对A1应用旋转矩阵
	var p = Cesium.Matrix4.multiplyByPoint(m4, A1, new Cesium.Cartesian3());
	// 新的A的坐标
	var p2 = Cesium.Cartesian3.add(p, B, new Cesium.Cartesian3());
	return p2;
}


VFG.EModel.prototype.rotatedPointByAngle=function(position_A, position_B, angle) {
    //以B点为原点建立局部坐标系（东方向为x轴,北方向为y轴,垂直于地面为z轴），得到一个局部坐标到世界坐标转换的变换矩阵
    var localToWorld_Matrix = Cesium.Transforms.eastNorthUpToFixedFrame(position_B);
    //求世界坐标到局部坐标的变换矩阵
    var worldToLocal_Matrix = Cesium.Matrix4.inverse(localToWorld_Matrix, new Cesium.Matrix4());
    //B点在局部坐标的位置，其实就是局部坐标原点
    var localPosition_B = Cesium.Matrix4.multiplyByPoint(worldToLocal_Matrix, position_B, new Cesium.Cartesian3());
    //A点在以B点为原点的局部的坐标位置
    var localPosition_A = Cesium.Matrix4.multiplyByPoint(worldToLocal_Matrix, position_A, new Cesium.Cartesian3());
    //根据数学公式A点逆时针旋转angle度后在局部坐标系中的x,y,z位置
    var new_x = localPosition_A.x * Math.cos(Cesium.Math.toRadians(angle)) + localPosition_A.y *   Math.sin(Cesium.Math.toRadians(angle));
    var new_y = localPosition_A.y * Math.cos(Cesium.Math.toRadians(angle)) - localPosition_A.x * Math.sin(Cesium.Math.toRadians(angle));
    var new_z = localPosition_A.z;
    //最后应用局部坐标到世界坐标的转换矩阵求得旋转后的A点世界坐标
    return Cesium.Matrix4.multiplyByPoint(localToWorld_Matrix, new Cesium.Cartesian3(new_x, new_y, new_z), new Cesium.Cartesian3());
}

VFG.EModel.prototype.destroy = function() {
	let _this=this;
	if(this.primity){
		this.viewer.scene.primitives.remove(this.primity);
	}
	if(this.antennaMap){
		_this.antennaMap.forEach(function (value,key){
			try{
				_this.viewer.entities.removeById(key);
			}catch (e) {
			}finally{
				_this.antennaMap.delete(key);
			}
		});
	}
	delete this.antennaMap
	delete this.orientation
	delete this.position
	delete this.primity
	delete this.options
	delete this.model
    delete this.viewer
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="PModel.js" />
VFG.PModel=function(viewer, options) {
	this.viewer = viewer;
	this.options = options;
	this.parentId= options.parentId||'';
	this.id= options.id;
	this.name= options.name||'';
	this.code= options.code||'';
	this.type= options.type||'';
	this.position=options.position||null;
	this.orientation=options.orientation||{};
	this.model=options.thing||{};
	this.attribute=options.attribute||{};
	this.propertys=options.propertys||[];
	this.init();
}
VFG.PModel.prototype.init = function() {
	let _this=this;
	var param={
			id: this.id,
			name :this.name,
			url :this.model.url||'',
			modelMatrix : this.getModelMatrix(),
			scale :this.model.scale*1||1,
			show : this.model.show||true,   
			minimumPixelSize:this.model.minimumPixelSize||0,
			allowPicking : this.model.allowPicking||true,        
			debugShowBoundingVolume : this.model.debugShowBoundingVolume||false, 
			debugWireframe : this.model.debugWireframe||false, 
			backFaceCulling:this.model.backFaceCulling||false, 
			shadows: this.model.shadows||false,   
	}
	if('1'== this.model.distanceDisplayCondition){
		param.distanceDisplayCondition=VFG.Util.getDistanceDisplayCondition( this.model.distanceNear, this.model.distanceFar);	
	}
	if('1'== this.model.silhouette){
		param.silhouetteColor= this.model.silhouetteColor? Cesium.Color.fromCssColorString( this.model.silhouetteColor):Cesium.Color.BLACK;	
		param.silhouetteSize= this.model.silhouetteSize*1||0;	
	}
	if('1'== this.model.fill){
		param.color= this.model.fillColor? Cesium.Color.fromCssColorString( this.model.fillColor):Cesium.Color.BLACK;	
	}
	this.primity = this.viewer.scene.primitives.add(Cesium.Model.fromGltf(param));
	this.primity.readyPromise.then(function(model) {
		if(_this.success){
			_this.success(model)
		}
	}).otherwise(function(error){
		if(_this.error){
			_this.error(error);
		}
    });
};
VFG.PModel.prototype.getModelMatrix=function(){
    var hpRoll = new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(this.orientation.heading || 0), Cesium.Math.toRadians(this.orientation.pitch || 0), Cesium.Math.toRadians(this.orientation.roll || 0));
    var fixedFrameTransform = Cesium.Transforms.eastNorthUpToFixedFrame;
    let cartesian3=Cesium.Cartesian3.fromDegrees(this.position.x*1, this.position.y*1,this.position.z*1);
    var modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(cartesian3, hpRoll, this.viewer.scene.globe.ellipsoid, fixedFrameTransform);
    return modelMatrix;
}

VFG.PModel.prototype.getRadius=function(){
    return this.primity.boundingSphere.radius;
}


VFG.PModel.prototype.on=function(type,callback){
	if('success'==type){
		this.success=callback;
	}
	if('error'==type){
		this.error=callback;
	}
}

VFG.PModel.prototype.update=function(param){

	if(param.position){
		this.position=param.position;
	}
	
	if(param.orientation){
		if(this.orientation.pitch){
			this.orientation.pitch=param.orientation.pitch;
		}
		if(this.orientation.heading){
			this.orientation.heading=param.orientation.heading;
		}
		if(this.orientation.roll){
			this.orientation.roll=param.orientation.roll;
		}
	}
	
	if(this.primity){
		this.primity.modelMatrix=this.getModelMatrix();
	}
}

VFG.PModel.prototype.updatePosition=function(position){
	this.position=position;
	if(this.primity){
		this.primity.modelMatrix=this.getModelMatrix();
	}
}

VFG.PModel.prototype.updateAttribute=function(attribute){
	this.attribute=attribute;
	if(attribute && attribute.name){
		this.name=attribute.name;
		this.attribute.name=attribute.name;
	}
	if(attribute && attribute.parentId){
		this.parentId=attribute.parentId;
		this.attribute.parentId=attribute.parentId;
	}
	
	if(attribute && attribute.code){
		this.attribute.code=attribute.code;
		this.code=attribute.code;
	}
	if(attribute && attribute.sort){
		this.attribute.sort=attribute.sort;
	}
}

/**
 * 缩放
 */
VFG.PModel.prototype.updateScale=function(scale){
	this.model.scale=scale;
	if(this.primity){
		this.primity.scale=this.model.scale*1;
	}
}

VFG.PModel.prototype.updateHeading=function(heading){
	this.orientation.heading=heading;
	if(this.primity){
		this.primity.modelMatrix=this.getModelMatrix();
	}
}

VFG.PModel.prototype.updatePitch=function(pitch){
	this.orientation.pitch=pitch;
	if(this.primity){
		this.primity.modelMatrix=this.getModelMatrix();
	}
}

VFG.PModel.prototype.updateRoll=function(roll){
	this.orientation.roll=roll;
	if(this.primity){
		this.primity.modelMatrix=this.getModelMatrix();
	}
}

VFG.PModel.prototype.updateMinimumPixelSize=function(minimumPixelSize){
	this.model.minimumPixelSize=minimumPixelSize;
	if(this.primity){
		this.primity.minimumPixelSize=minimumPixelSize;
	}
}

VFG.PModel.prototype.updateColor=function(color){
	this.model.fillColor=color;
	if(this.primity){
		this.primity.color=color? Cesium.Color.fromCssColorString(color):Cesium.Color.WHITE;	
	}
}

VFG.PModel.prototype.updateSilhouetteColor=function(silhouetteColor){
	this.model.silhouetteColor=silhouetteColor;
	if(this.primity){
		this.primity.silhouetteColor=silhouetteColor? Cesium.Color.fromCssColorString(silhouetteColor):Cesium.Color.WHITE;	
	}
}
VFG.PModel.prototype.updateSilhouetteSize=function(silhouetteSize){
	this.model.silhouetteSize=silhouetteSize;
	if(this.primity){
		this.primity.silhouetteSize=silhouetteSize*1;	
	}
}

VFG.PModel.prototype.updateDistanceDisplay=function(display){
	if(display.distanceNear){
		this.model.distanceNear=display.distanceNear;
	}
	if(display.distanceFar){
		this.model.distanceFar=display.distanceFar;
	}
	if(this.primity){
		this.primity.distanceDisplayCondition=VFG.Util.getDistanceDisplayCondition(this.model.distanceNear||0,this.model.distanceFar||5000);	
	}
}

VFG.PModel.prototype.isDistanceDisplay=function(display){
	this.model.distanceDisplayCondition=display;
	if(this.primity){
		if('1'===display){
			this.primity.distanceDisplayCondition=VFG.Util.getDistanceDisplayCondition(this.model.distanceNear||0,this.model.distanceFar||5000);	
		}else{
			this.primity.distanceDisplayCondition=null;	
		}
	}
}

VFG.PModel.prototype.isSilhouette=function(silhouette){
	this.model.silhouette=silhouette;
	if(this.primity){
		if('1'===silhouette){
			this.primity.silhouetteColor= this.model.silhouetteColor? Cesium.Color.fromCssColorString( this.model.silhouetteColor):Cesium.Color.WHITE;	
			this.primity.silhouetteSize= this.model.silhouetteSize*1||0;	
		}else{
			this.primity.silhouetteColor= Cesium.Color.WHITE;	
			this.primity.silhouetteSize= 0;	
		}
	}
}

VFG.PModel.prototype.isFill=function(fill){
	this.model.fill=fill;
	if(this.primity){
		if('1'===fill){
			this.primity.color= this.model.fillColor? Cesium.Color.fromCssColorString( this.model.fillColor):Cesium.Color.WHITE;	
		}else{
			this.primity.color= Cesium.Color.WHITE;	
		}
	}
}

VFG.PModel.prototype.isShadows=function(shadows){
	this.model.shadows=shadows;
	if(this.primity){
		if('1'===shadows){
			this.primity.shadows= this.model.shadows*1;	
		}else{
			this.primity.shadows= this.model.shadows*1;	
		}
	}
}

VFG.PModel.prototype.selected=function(){
	if(this.primity){
		this.primity.silhouetteColor= Cesium.Color.YELLOW;	
		this.primity.silhouetteSize= 2;	
	}
}

VFG.PModel.prototype.unselected=function(){
	if(this.primity){
		this.primity.silhouetteColor= this.model.silhouetteColor? Cesium.Color.fromCssColorString( this.model.silhouetteColor):Cesium.Color.WHITE;	
		this.primity.silhouetteSize= 0;	
	}
}

VFG.PModel.prototype.updateProperty= function(property) {
	var _this = this;
	if(_this.propertys){
		for(let index in _this.propertys){
			if(property.id==_this.propertys[index].id){
				_this.propertys.splice(index,1,property);
				return;
			}
		}
		_this.propertys.push(property);
	}
};

VFG.PModel.prototype.removeProperty= function(id) {
	var _this = this;
	if(_this.propertys){
		for(let index in _this.propertys){
			if(id==_this.propertys[index].id){
				_this.propertys.splice(index,1);
				return;
			}
		}
	}
};

VFG.PModel.prototype.destroy = function() {
	let _this=this;
	if(this.primity){
		this.viewer.scene.primitives.remove(this.primity);
	}
	if(this.antennaMap){
		_this.antennaMap.forEach(function (value,key){
			try{
				_this.viewer.entities.removeById(key);
			}catch (e) {
			}finally{
				_this.antennaMap.delete(key);
			}
		});
	}
	delete this.antennaMap
	delete this.orientation
	delete this.position
	delete this.primity
	delete this.options
	delete this.model
    delete this.viewer
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="TModel.js" />
/**
 * tileset.json
 */
VFG.TModel=function(viewer, options) {
	this.viewer = viewer;
	this.options = options;
	this.parentId= options.parentId||'';
	this.id= options.id;
	this.name= options.name||'';
	this.code= options.code||'';
	this.type= options.type||'';
	this.position=options.position||{};
	this.orientation=options.orientation||{};
	this.model=options.thing||{};
	this.attribute=options.attribute||{};
	this.propertys=options.propertys||[];
	this.featureGroup=new Map();
	this.cacheHideFeatureGroup=new Map();
	this.init();
}
VFG.TModel.prototype.init = function() {
	let _this=this;
	this.primity = this.viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
		id : this.id,
		name :this.name,
		code:this.code,
		type:this.type,
		url :this.model.url||'',
		show :this.model.show||true,    
	    preferLeaves:(this.model && this.model.preferLeaves && this.model.preferLeaves=='1')?true:false,
		/*imageBasedLightingFactor :Cesium.Cartesian2(1.0, 1.0),*/
		loadSiblings:true,
		baseScreenSpaceError:this.model.baseScreenSpaceError ? this.model.baseScreenSpaceError*1: 1024,
		skipScreenSpaceErrorFactor:this.model.skipScreenSpaceErrorFactor ? this.model.skipScreenSpaceErrorFactor*1: 16,
		maximumMemoryUsage:this.model.maximumMemoryUsage ? this.model.maximumMemoryUsage*1: 512,
		maximumScreenSpaceError : this.model.maximumScreenSpaceError ? this.model.maximumScreenSpaceError*1: 16,
		skipLevelOfDetail : this.model.skipLevelOfDetail ? (this.model.skipLevelOfDetail=='on'?true:false): false,
		maximumNumberOfLoadedTiles : this.model.maximumNumberOfLoadedTiles ? this.model.maximumNumberOfLoadedTiles*1: 2048, //最大加载瓦片个数		
		backFaceCulling:true,
	    cullWithChildrenBounds : true,
	    dynamicScreenSpaceError:false,
	    dynamicScreenSpaceErrorDensity:0.00278,
	    dynamicScreenSpaceErrorFactor:4,
	    dynamicScreenSpaceErrorHeightFalloff:0.25,
	    skipLevelOfDetail:true,
	    skipLevels:1,
	    immediatelyLoadDesiredLevelOfDetail:false,
	    loadSiblings:false,
	    luminanceAtZenith:0.2,
	    classificationType:Cesium.ClassificationType.NONE,
	    shadows:Cesium.ShadowMode.ENABLED,
	    lightColor : new Cesium.Cartesian3(1,1,1),
	  /*  imageBasedLightingFactor:new Cesium.Cartesian2(1.0, 1.0)	*/
	}));
	
	this.primity.readyPromise.then(function(tileset) {
		
		tileset.tileVisible.addEventListener(function(tile) {
			var content = tile.content;
			var innerContents = content.innerContents;
			if (Cesium.defined(innerContents)) {
				var length = innerContents.length;
				for (var i = 0; i < length; ++i) {
					_this.processContentFeatures(innerContents[i], null);
				}
			} else {
				_this.processContentFeatures(content, null);
			}
			
			
/*			var content = tile.content;
		    var featuresLength = content.featuresLength;
		    for (var i = 0; i < featuresLength; ++i) {
		        let feature=content.getFeature(i)
		        if (feature instanceof Cesium.Cesium3DTileFeature) {
			        var propertyNames = feature.getPropertyNames();
			        var length = propertyNames.length;
			        for (var j = 0; j < length; ++j) {
			            var propertyName = propertyNames[j];
			            if('CFC17'==feature.getProperty(propertyName)){
			            	 console.log(propertyName + ': ' + feature.getProperty(propertyName));
			            }
			        }
			    }		        
		    }*/
		});
		
		
    	if(_this.position && !$.isEmptyObject(_this.position)){
    		tileset._root.transform=_this.getModelMatrix();
    	}else{
            var heightOffset =0;  //高度
            var boundingSphere = tileset.boundingSphere; 
            var cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center);
            var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);
            var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, heightOffset);
            var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
            tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
	    	var param=VFG.Util.getCenterForModel(tileset,tileset._root.transform);
	    	if(param){
		    	_this.position.x=param.x;
		    	_this.position.y=param.y;
		    	_this.position.z=param.z;
		    	_this.orientation.heading=param.rotation_y;
		    	_this.orientation.pitch=param.rotation_x;
		    	_this.orientation.roll=param.rotation_z;
	    	}
    	}
	    if(_this.success){
	    	_this.success({
	    		position:_this.position,
	    		orientation:_this.orientation,
	    	});
		}
	}).otherwise(function(error){
	    if(_this.error){
	    	_this.error(error);
	    }
	    console.log(error);
    });
	
	this.primity.allTilesLoaded.addEventListener(function() {
	    if(_this.loaded){
	    	_this.loaded(_this);
	    }
    });
	
	this.primity.loadProgress.addEventListener(function(numberOfPendingRequests, numberOfTilesProcessing) {
	   if(_this.Loading){
		   _this.Loading(numberOfPendingRequests, numberOfTilesProcessing)
	   }
	});
	
	

	
	
	if(this.model.cacheFeature=='1'){
/*		this.primity.tileVisible.addEventListener(function(tile) {
			var content = tile.content;
			
		    if (content instanceof Cesium.Batched3DModel3DTileContent) {
			    var featuresLength = content.featuresLength;
			    for (var i = 0; i < featuresLength; i++) {
			    	var id=content.getFeature(i).getProperty('id');
			    	var name=content.getFeature(i).getProperty('name');
			    	if("CFC17"==name){
			    		console.log(content.getFeature(i));
			    	}
			    	if(_this.featureGroup.has(name)){
			    		_this.featureGroup.get(name).set(content.getFeature(i),content.getFeature(i));
			    	}else{
			    		_this.featureGroup.set(name,new Map());
			    		_this.featureGroup.get(name).set(content.getFeature(i),content.getFeature(i));
			    	}
					_this.cacheHideFeatureGroup.forEach(function (value, key, map) {
						if(name.indexOf(key)!=-1){
							content.getFeature(i).show=false;
						}
					})
			    }
		    }
		});*/
		this.primity.tileUnload.addEventListener(function (tile) {
		   if(_this.tileUnload){
			   _this.tileUnload(tile)
		   }
/*			var content = tile.content;
		    var featuresLength = content.featuresLength;
		    for (var i = 0; i < featuresLength; i++) {
		    	_this.featureGroup.delete(content.getFeature(i).getProperty('name'));
		    }*/
		});
	}

};

VFG.TModel.prototype.showFeatureGroup=function(groupNamePrefix){
	if(this.model.cacheFeature=='1'){
		let _this=this;
		if(_this.cacheHideFeatureGroup.has(groupNamePrefix)){
			_this.featureGroup.forEach(function (value, key, map){
				if(key.indexOf(groupNamePrefix)!=-1){
					value.forEach(function (fvalue, fkey, fmap) {
						if(Cesium.defined(fvalue)){
							try{
								fvalue.show=true;
							}catch(err){
							}
						}
					})
				}
			});
			_this.cacheHideFeatureGroup.delete(groupNamePrefix)
		}
	}
}

VFG.TModel.prototype.hideFeatureGroup=function(groupNamePrefix){
	if(this.model.cacheFeature=='1'){
		let _this=this;
		if(!_this.cacheHideFeatureGroup.has(groupNamePrefix)){
			_this.cacheHideFeatureGroup.set(groupNamePrefix,"")
			_this.featureGroup.forEach(function (value, key, map){
				if(key.indexOf(groupNamePrefix)!=-1){
					value.forEach(function (fvalue, fkey, fmap) {
						if(Cesium.defined(fvalue)){
							try{
								fvalue.show=false;
							}catch(err){
							}
						}
					})
				}
			});
		}
	}
}

VFG.TModel.prototype.getFeatureGroup=function(groupNamePrefix){
	return this.featureGroup;
}

VFG.TModel.prototype.processContentFeatures=function(content, callback) {
	let _this=this;
	var featuresLength = content.featuresLength;
	for (var i = 0; i < featuresLength; ++i) {
    	var id=content.getFeature(i).getProperty('id');
    	var name=content.getFeature(i).getProperty('name');
    	if(_this.featureGroup.has(name)){
    		_this.featureGroup.get(name).set(content.getFeature(i),content.getFeature(i));
    	}else{
    		_this.featureGroup.set(name,new Map());
    		_this.featureGroup.get(name).set(content.getFeature(i),content.getFeature(i));
    	}
		_this.cacheHideFeatureGroup.forEach(function (value, key, map) {
			if(name.indexOf(key)!=-1){
				content.getFeature(i).show=false;
			}
		})
 	}
}

VFG.TModel.prototype.getModelMatrix=function(){
   var transformPosition =Cesium.Cartesian3.fromDegrees(this.position.x*1, this.position.y*1,this.position.z*1);
   var matrix = Cesium.Transforms.eastNorthUpToFixedFrame(transformPosition);
   var scale = Cesium.Matrix4.fromUniformScale(this.model.scale*1);
   Cesium.Matrix4.multiply(matrix, scale, matrix);
   var rotationX = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(this.orientation.pitch || 0));
   var rotationY = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(this.orientation.heading || 0));
   var rotationZ = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(this.orientation.roll || 0));
   var rotationTranslationX = Cesium.Matrix4.fromRotationTranslation(rotationX);
   var rotationTranslationY = Cesium.Matrix4.fromRotationTranslation(rotationY);
   var rotationTranslationZ = Cesium.Matrix4.fromRotationTranslation(rotationZ);
   Cesium.Matrix4.multiply(matrix, rotationTranslationX, matrix);
   Cesium.Matrix4.multiply(matrix, rotationTranslationY, matrix);
   Cesium.Matrix4.multiply(matrix, rotationTranslationZ, matrix);
   return matrix;
}

VFG.TModel.prototype.getRadius=function(){
    return this.primity.boundingSphere.radius;
}

VFG.TModel.prototype.on=function(type,callback){
	if('success'==type){
		this.success=callback;
	}
	if('error'==type){
		this.error=callback;
	}
	if('loaded'==type){
		this.loaded=callback;
	}
	if('Loading'==type){
		this.Loading=callback;
	}
	if('tileLoad'==type){
		this.tileLoad=callback;
	}
	if('tileUnload'==type){
		this.tileUnload=callback;
	}
}

VFG.TModel.prototype.update=function(param){
	if(param.position){
		this.position=param.position;
	}
	if(param.orientation){
		if(this.orientation.pitch){
			this.orientation.pitch=param.orientation.pitch;
		}
		if(this.orientation.heading){
			this.orientation.heading=param.orientation.heading;
		}
		if(this.orientation.roll){
			this.orientation.roll=param.orientation.roll;
		}
	}
	if(this.primity){
		this.primity._root.transform=this.getModelMatrix();
	}
}

VFG.TModel.prototype.updateThing=function(thing){
	if(thing){
		if(thing.preferLeaves){
			this.model.preferLeaves=thing.preferLeaves;
		}
		if(thing.skipLevels){
			this.model.skipLevels=thing.skipLevels;
		}
		if(thing.baseScreenSpaceError){
			this.model.baseScreenSpaceError=thing.baseScreenSpaceError;
		}
		if(thing.skipScreenSpaceErrorFactor){
			this.model.skipScreenSpaceErrorFactor=thing.skipScreenSpaceErrorFactor;
		}
		if(thing.maximumMemoryUsage){
			this.model.maximumMemoryUsage=thing.maximumMemoryUsage;
		}
		if(thing.maximumScreenSpaceError){
			this.model.maximumScreenSpaceError=thing.maximumScreenSpaceError;
		}
		if(thing.skipLevelOfDetail){
			this.model.skipLevelOfDetail=thing.skipLevelOfDetail;
		}
		if(thing.maximumNumberOfLoadedTiles){
			this.model.maximumNumberOfLoadedTiles=thing.maximumNumberOfLoadedTiles;
		}
	}
}

VFG.TModel.prototype.updatePosition=function(position){
	this.position=position;
	if(this.primity){
		this.primity._root.transform=this.getModelMatrix();
	}
}

VFG.TModel.prototype.updateAttribute=function(attribute){
	this.attribute=attribute;
	if(attribute && attribute.name){
		this.name=attribute.name;
		this.attribute.name=attribute.name;
	}
	if(attribute && attribute.parentId){
		this.parentId=attribute.parentId;
		this.attribute.parentId=attribute.parentId;
	}
	
	if(attribute && attribute.code){
		this.attribute.code=attribute.code;
		this.code=attribute.code;
	}
	if(attribute && attribute.sort){
		this.attribute.sort=attribute.sort;
	}
}

/**
 * 缩放
 */
VFG.TModel.prototype.updateScale=function(scale){
	this.model.scale=scale;
	if(this.primity){
		this.primity._root.transform=this.getModelMatrix();
	}
}

VFG.TModel.prototype.updateHeading=function(heading){
	this.orientation.heading=heading;
	if(this.primity){
		this.primity._root.transform=this.getModelMatrix();
	}
}

VFG.TModel.prototype.updatePitch=function(pitch){
	this.orientation.pitch=pitch;
	if(this.primity){
		this.primity._root.transform=this.getModelMatrix();
	}
}

VFG.TModel.prototype.updateRoll=function(roll){
	this.orientation.roll=roll;
	if(this.primity){
		this.primity._root.transform=this.getModelMatrix();
	}
}

/**
 * 更新属性
 */
VFG.TModel.prototype.updateProperty= function(property) {
	var _this = this;
	if(_this.propertys){
		for(let index in _this.propertys){
			if(property.id==_this.propertys[index].id){
				_this.propertys.splice(index,1,property);
				return;
			}
		}
		_this.propertys.push(property);
	}
};

/**
 * 移除属性
 */
VFG.TModel.prototype.removeProperty= function(id) {
	var _this = this;
	if(_this.propertys){
		for(let index in _this.propertys){
			if(id==_this.propertys[index].id){
				_this.propertys.splice(index,1);
				return;
			}
		}
	}
};

VFG.TModel.prototype.destroy = function() {
	let _this=this;
	if(this.primity){
		this.viewer.scene.primitives.remove(this.primity);
	}
	this.featureGroup.clear();
	delete this.featureGroup
	delete this.orientation
	delete this.position
	delete this.primity
	delete this.options
	delete this.model
    delete this.viewer
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="VModel.js" />
VFG.VModel = function(viewer,options) {
	this.option = Cesium.defaultValue(options, Cesium.defaultValue.EMPTY_OBJECT);
	this.viewer = Cesium.defaultValue(viewer, undefined);
	this.options = options;
	this.parentId= options.parentId||'';
	this.id= options.id;
	this.name= options.name||'';
	this.code= options.code||'';
	this.type= options.type||'';
	this.position=options.position||null;
	this.orientation=options.orientation||{};
	this.model=options.thing||{};
	this.attribute=options.attribute||{};
	this.propertys=options.propertys||[];
	this.videoEle=options.videoEle||null;
	this.isCreateVideoEle=false;
	
	this.primitive;
	this.vertices=[];
	this.normals=[];
	this.colors=[];
	this.uvs=[];
	
	this.geometry={
		vertices: [],
		normals: [],
		colors: [],
		uvs: [],
		indices:[],
	}
	this.init();
}

VFG.VModel.prototype.init=function(){
	this.read();
}

/**
 * read
 */
VFG.VModel.prototype.read=function(){
	var _this=this;
	var request = new XMLHttpRequest();
	request.onreadystatechange = function() {
		if (request.readyState == 4 && request.status != 404) {
			try{
				_this.parse(request.responseText);
				_this.create(_this.geometry);
				if(_this.success){
					_this.success(_this);
				}
				if(_this.complete){
					_this.complete();
				}
			}catch (e) {
				if(_this.error){
					_this.error(e);
				}
				if(_this.complete){
					_this.complete();
				}
			}
		}
	};
	request.onerror=function(error){
		if(_this.error){
			_this.error(error);
		}
		if(_this.complete){
			_this.complete();
		}
	};
	request.ontimeout=function(error){
		if(_this.error){
			_this.error('加载超时！');
		}
		if(_this.complete){
			_this.complete();
		}
	};
	request.open('GET', _this.model.url, true); 
	request.send();
	if(_this.complete){
		_this.complete();
	}
}

/**
 * 创建图元
 */
VFG.VModel.prototype.create=function(geometry){
	var _this=this;
	var normals=geometry.normals;
	var uvs=geometry.uvs;
	var vertices=geometry.vertices;
	var indices=new Uint16Array(geometry.indices);
	_this.primitive=_this.viewer.scene.primitives.add(new Cesium.Primitive({
        geometryInstances: new Cesium.GeometryInstance({
            geometry: new Cesium.Geometry({
                attributes: {
                    position: new Cesium.GeometryAttribute({
                        componentDatatype: Cesium.ComponentDatatype.DOUBLE,
                        componentsPerAttribute: 3,
                        values: vertices
                    }),
                    normal: new Cesium.GeometryAttribute({
                        componentDatatype: Cesium.ComponentDatatype.FLOAT,
                        componentsPerAttribute: 3,
                        values: normals
                    }),
                    st: new Cesium.GeometryAttribute({
                        componentDatatype: Cesium.ComponentDatatype.FLOAT,
                        componentsPerAttribute: 2,
                        values: uvs
                    }),
                },
               // indices: indices, 
                pickPrimitive : this,
                primitiveType: Cesium.PrimitiveType.TRIANGLES,
                boundingSphere:Cesium.BoundingSphere.fromVertices(vertices),
            }),
            id : _this.id,
            modelMatrix: _this.getMatrix(),
        }),
       appearance: new Cesium.MaterialAppearance({
    	    material: _this.getMaterial(),
            faceForward : true, 
            closed: false 
        }),
        asynchronous: false
    }));
}

VFG.VModel.prototype.getMaterial = function() {
	var _self = this;
	if(_self.videoEle){
		_self.canplaythrough=function () {
	    	_self.viewer.clock.onTick.addEventListener(_self.activeVideoListener, _self);
	    };
	    _self.videoEle.addEventListener("canplaythrough",_self.canplaythrough);
	    let material = Cesium.Material.fromType('Image');
	    material.uniforms.image =_self.videoEle;
	    return material;
	}
	else if(('0'== _self.model.videoType && _self.model.videoUrl ) || 
			('1'== _self.model.videoType && ( _self.model.videoUrl  ||  _self.model.videoId ) ) ){
		_self.videoEle=_self.createVideoEle();
		_self.isCreateVideoEle=true;
		_self.canplaythrough=function () {
	    	_self.viewer.clock.onTick.addEventListener(_self.activeVideoListener, _self);
	    };
	    _self.videoEle.addEventListener("canplaythrough",_self.canplaythrough );
	    let material = Cesium.Material.fromType('Image');
	    material.uniforms.image =_self.videoEle;
	    return material;
	}
	
	
	else{
		if(_self.model.thumbnail){
			return new Cesium.Material({ 
				fabric : {
	     		    type : 'Image',
	     		    uniforms : {
	     		      image : _self.model.thumbnail
	     		    }
	     		}
	  		})
		}else{
			return new Cesium.Material({
			    fabric : {
			        type : 'Color',
			        uniforms : {
			            color : Cesium.Color.BLACK.withAlpha(0.5)
			        }
			    }
			})
		}
	}
};

VFG.VModel.prototype.getRadius=function(){
	if(this.primitive){
		return this.primitive._instanceBoundingSpheres[0].radius
	}
}

VFG.VModel.prototype.createVideoEle = function () {
	var _self = this;
	 var r = document.createElement("VIDEO");
	var src;
	if('0'==_self.model.videoType){
		src=_self.model.videoUrl;
	}
	else{
    	_self.webRtcServer= new WebRtcStreamer(r,_self.model.webRTCUrl);
	    _self.webRtcServer.connect(_self.model.videoId,'','');
	}
	this.videoId = "visualDomId"+_self.option.id;
    var t = document.createElement("SOURCE");
    t.type = "video/mp4",
    t.src = src;
    var i = document.createElement("SOURCE");
    i.type = "video/quicktime",
    i.src = src;
    return r.setAttribute("autoplay", !0),
    r.setAttribute("loop", !0),
    r.setAttribute("crossorigin", !0),
    r.setAttribute("muted", "muted"),
    r.appendChild(t),
    r.appendChild(i),
    r.style.display = "none",
    document.body.appendChild(r),
    r
}

VFG.VModel.prototype.getMatrix = function() {
	var _this = this;
	var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Cartesian3.fromDegrees(this.position.x*1, this.position.y*1,this.position.z*1));
	var scaleMatrix = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(_this.model.scaleX?_this.model.scaleX*1:1,_this.model.scaleY?_this.model.scaleY*1:1,_this.model.scaleZ?_this.model.scaleZ*1:1));
		modelMatrix = Cesium.Matrix4.multiply(modelMatrix, scaleMatrix, new Cesium.Matrix4());
		var hprRotation = Cesium.Matrix3.fromHeadingPitchRoll(new Cesium.HeadingPitchRoll(
				Cesium.Math.toRadians(this.orientation.heading || 0), 
				Cesium.Math.toRadians(this.orientation.pitch || 0), 
				Cesium.Math.toRadians(this.orientation.roll || 0)));
	var hpr = Cesium.Matrix4.fromRotationTranslation(hprRotation,new Cesium.Cartesian3(0.0, 0.0, 0.0));
	return Cesium.Matrix4.multiply(modelMatrix, hpr, modelMatrix);
}; 

VFG.VModel.prototype.activeVideoListener = function (e) {
	var _this=this;
    try {
        if (_this._videoPlay && _this.videoEle.paused) _this.videoEle.play();
    } catch (e) {}
}

VFG.VModel.prototype.deActiveVideo = function (e) {
	this.viewer.clock.onTick.removeEventListener(this.activeVideoListener, this);
}

VFG.VModel.prototype.update=function(param){
	if(param.position){
		this.position=param.position;
	}
	if(param.orientation){
		if(param.orientation.pitch){
			this.orientation.pitch=param.orientation.pitch;
		}
		if(param.orientation.heading){
			this.orientation.heading=param.orientation.heading;
		}
		if(param.orientation.roll){
			this.orientation.roll=param.orientation.roll;
		}
	}
	if(param.scale){
		if(param.scale.x){
			this.model.scaleX=param.scale.x;
		}
		if(param.scale.y){
			this.model.scaleY=param.scale.y;
		}
		if(param.scale.z){
			this.model.scaleZ=param.scale.z;
		}
	}
	if(this.primitive){
		this.primitive.modelMatrix=this.getMatrix();
	}
}

VFG.VModel.prototype.updatePosition=function(position){
	this.position=position;
	if(this.primitive){
		this.primitive.modelMatrix=this.getMatrix();
	}
}

VFG.VModel.prototype.updateHeading=function(heading){
	this.orientation.heading=heading;
	if(this.primitive){
		this.primitive.modelMatrix=this.getMatrix();
	}
}

VFG.VModel.prototype.updatePitch=function(pitch){
	this.orientation.pitch=pitch;
	if(this.primitive){
		this.primitive.modelMatrix=this.getMatrix();
	}
}

VFG.VModel.prototype.updateRoll=function(roll){
	this.orientation.roll=roll;
	if(this.primitive){
		this.primitive.modelMatrix=this.getMatrix();
	}
}

VFG.VModel.prototype.updateScaleX=function(scaleX){
	this.model.scaleX=scaleX;
	if(this.primitive){
		this.primitive.modelMatrix=this.getMatrix();
	}
}

VFG.VModel.prototype.updateScaleY=function(scaleY){
	this.model.scaleY=scaleY;
	if(this.primitive){
		this.primitive.modelMatrix=this.getMatrix();
	}
}

VFG.VModel.prototype.updateScaleZ=function(scaleZ){
	this.model.scaleZ=scaleZ;
	if(this.primitive){
		this.primitive.modelMatrix=this.getMatrix();
	}
}

VFG.VModel.prototype.updateVideo=function(){
	var _this=this;
	this.destroyVideo();
	if(this.primitive){
		this.primitive.appearance=new Cesium.MaterialAppearance({
    	    material: _this.getMaterial(),
            faceForward : true, 
            closed: false 
        })
	}
}

VFG.VModel.prototype.updateObj=function(param){
}


VFG.VModel.prototype.updateThing=function(thing){
	if(thing){
		if(thing.name){
			this.name=thing.name;
		}
		if(thing.code){
			this.code=thing.code;
		}
		if(thing.isRelative){
			this.model.isRelative=thing.isRelative;
		}
		if(thing.videoType){
			this.model.videoType=thing.videoType;
		}
		if(thing.videoUrl){
			this.model.videoUrl=thing.videoUrl;
		}
		if(thing.webRTCUrl){
			this.model.webRTCUrl=thing.webRTCUrl;
		}
		if(thing.videoId){
			this.model.videoId=thing.videoId;
		}
		if(thing.thumbnail){
			this.model.thumbnail=thing.thumbnail;
		}
		if(thing.url){
			this.model.url=thing.url;
		}
	}
}

VFG.VModel.prototype.addListener=function(type,callback){
	if('success'==type){
		this.success=callback;
	}
	if('error'==type){
		this.error=callback;
	}
	if('complete'==type){
		this.complete=callback;
	}
}

VFG.VModel.prototype.removeListener=function(type){
	if('beforeSend'==type){
		this.beforeSend=null;
	}
	if('success'==type){
		this.success=null;
	}
	if('error'==type){
		this.error=null;
	}
	if('complete'==type){
		this.complete=null;
	}
}

VFG.VModel.prototype.destroyVideo=function(){
	if(this.videoEle){
	  this.videoEle.removeEventListener('canplaythrough',this.canplaythrough);
  }
  if(this.webRtcServer){
	  this.webRtcServer.disconnect();
  }
  if(this.isCreateVideoEle){
	  this.videoEle && this.videoEle.parentNode.removeChild(this.videoEle);
	  this.videoEle=null
  }
}

VFG.VModel.prototype.destroyObj=function(){
  this.deActiveVideo();
  if(this.primitive){
	  this.viewer.scene.primitives.remove(this.primitive);
  }
  if(this.primitive){
	  this.viewer.scene.primitives.remove(this.primitive);
  }
  this.destroyVideo();
}


VFG.VModel.prototype.destroy = function () {
  this.destroyObj();
  delete this.webRtcServer,
  delete this.videoEle,
  delete this.options,
  delete this.model,
  delete this.primitive,
  delete this.viewer;
  return Cesium.destroyObject(this);
};

/*************************************obj模型解析*******************************************/
VFG.VModel.prototype.parse=function( text ) {
	var _this=this;
	if ( text.indexOf( '\r\n' ) !== - 1 ) {
		text = text.replace( /\r\n/g, '\n' );
	}

	if ( text.indexOf( '\\\n' ) !== - 1 ) {
		text = text.replace( /\\\n/g, '' );
	}

	var lines = text.split( '\n' );
	var line = '', lineFirstChar = '';
	var lineLength = 0;
	var result = [];

	// Faster to just trim left side of the line. Use if available.
	var trimLeft = ( typeof ''.trimLeft === 'function' );

	for ( var i = 0, l = lines.length; i < l; i ++ ) {

		line = lines[ i ];
		line = trimLeft ? line.trimLeft() : line.trim();
		lineLength = line.length;
		if ( lineLength === 0 ) continue;

		lineFirstChar = line.charAt( 0 );
		// @todo invoke passed in handler if any
		if ( lineFirstChar === '#' ) continue;

		if ( lineFirstChar === 'v' ) {
			var data = line.split( /\s+/ );
			switch ( data[ 0 ] ) {
				case 'v':
					_this.vertices.push(
						parseFloat( data[ 1 ] ),
						parseFloat( data[ 2 ] ),
						parseFloat( data[ 3 ] )
					);
					if ( data.length >= 7 ) {
						_this.colors.push(
							parseFloat( data[ 4 ] ),
							parseFloat( data[ 5 ] ),
							parseFloat( data[ 6 ] )
						);
					} else {
						_this.colors.push( undefined, undefined, undefined );
					}
					break;
				case 'vn':
					_this.normals.push(
						parseFloat( data[ 1 ] ),
						parseFloat( data[ 2 ] ),
						parseFloat( data[ 3 ] )
					);
					break;
				case 'vt':
					_this.uvs.push(
						parseFloat( data[ 1 ] ),
						parseFloat( data[ 2 ] )
					);
					break;

			}

		} else if ( lineFirstChar === 'f' ) {
			var lineData = line.substr( 1 ).trim();
			var vertexData = lineData.split( /\s+/ );
			var faceVertices = [];

			// Parse the face vertex data into an easy to work with format
			for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
				var vertex = vertexData[ j ];
				if ( vertex.length > 0 ) {
					var vertexParts = vertex.split( '/' );
					faceVertices.push( vertexParts );
					this.geometry.indices.push(vertexParts[0]*1-1);
				}
				
			}
			var v1 = faceVertices[ 0 ];
			for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
				var v2 = faceVertices[ j ];
				var v3 = faceVertices[ j + 1 ];
				_this.addFace(
					v1[ 0 ], v2[ 0 ], v3[ 0 ],
					v1[ 1 ], v2[ 1 ], v3[ 1 ],
					v1[ 2 ], v2[ 2 ], v3[ 2 ]
				);
			}
		} else {
			if ( line === '\0' ) continue;
		}
	}
}

VFG.VModel.prototype.addFace= function ( a, b, c, ua, ub, uc, na, nb, nc ) {
	var vLen = this.vertices.length;
	
	var ia = this.parseVertexIndex( a, vLen );
	var ib = this.parseVertexIndex( b, vLen );
	var ic = this.parseVertexIndex( c, vLen );

	this.addVertex( ia, ib, ic );
	this.addColor( ia, ib, ic );
	
	
	 this.geometry.indices.push(ia);
	 this.geometry.indices.push(ib);
	 this.geometry.indices.push(ic);
	

	// normals
	if ( na !== undefined && na !== '' ) {
		var nLen = this.normals.length;
		ia = this.parseNormalIndex( na, nLen );
		ib = this.parseNormalIndex( nb, nLen );
		ic = this.parseNormalIndex( nc, nLen );
		this.addNormal( ia, ib, ic );
	} else {
		this.addFaceNormal( ia, ib, ic );
	}

	// uvs
	if ( ua !== undefined && ua !== '' ) {
		var uvLen = this.uvs.length;
		ia = this.parseUVIndex( ua, uvLen );
		ib = this.parseUVIndex( ub, uvLen );
		ic = this.parseUVIndex( uc, uvLen );
		this.addUV( ia, ib, ic );
	} else {
		this.addDefaultUV();
	}
}

//use
VFG.VModel.prototype.addVertex=function ( a, b, c ) {
	var src = this.vertices;
	var dst = this.geometry.vertices;
	dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
	dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
	dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
}

//use
VFG.VModel.prototype.addNormal=function ( a, b, c ) {
	var src = this.normals;
	var dst = this.geometry.normals;
	dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
	dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
	dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
}

//use
VFG.VModel.prototype.addFaceNormal=function ( a, b, c ) {

	var src = this.vertices;
	var dst = this.geometry.normals;

	vA.fromArray( src, a );
	vB.fromArray( src, b );
	vC.fromArray( src, c );

	cb.subVectors( vC, vB );
	ab.subVectors( vA, vB );
	cb.cross( ab );

	cb.normalize();

	dst.push( cb.x, cb.y, cb.z );
	dst.push( cb.x, cb.y, cb.z );
	dst.push( cb.x, cb.y, cb.z );

}

//use
VFG.VModel.prototype.addColor= function ( a, b, c ) {

	var src = this.colors;
	var dst = this.geometry.colors;

	if ( src[ a ] !== undefined ) dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
	if ( src[ b ] !== undefined ) dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
	if ( src[ c ] !== undefined ) dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );

}

//use
VFG.VModel.prototype.addUV= function ( a, b, c ) {
	var src = this.uvs;
	var dst = this.geometry.uvs;
	dst.push( src[ a + 0 ], src[ a + 1 ] );
	dst.push( src[ b + 0 ], src[ b + 1 ] );
	dst.push( src[ c + 0 ], src[ c + 1 ] );
}

//use
VFG.VModel.prototype.addDefaultUV=function () {
	var dst = this.geometry.uvs;
	dst.push( 0, 0 );
	dst.push( 0, 0 );
	dst.push( 0, 0 );
}

VFG.VModel.prototype.parseVertexIndex=function ( value, len ) {
	var index = parseInt( value, 10 );
	return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
}

VFG.VModel.prototype.parseNormalIndex=function ( value, len ) {
	var index = parseInt( value, 10 );
	return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
}
VFG.VModel.prototype.parseUVIndex=function ( value, len ) {
	var index = parseInt( value, 10 );
	return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
}


;
///<jscompress sourcefile="CalculatorBillboard.js" />
VFG.CalculatorBillboard = function(viewer,options) {
	this.option = Cesium.defaultValue(options, Cesium.defaultValue.EMPTY_OBJECT);
	this.viewer = Cesium.defaultValue(viewer, undefined);
	this.options = options;
	this.parentId= options.parentId||'';
	this.id= options.id;
	this.name= options.name||'';
	this.code= options.code||'';
	this.type= options.type||'';
	this.position=options.position||null;
	this.orientation=options.orientation||{};
	this.model=options.thing||{};
	this.attribute=options.attribute||{};
	this.propertys=options.propertys||[];
	this.videoEle=options.videoEle||null;
	this.isCreateVideoEle=false;
	
	this.primitive;
	this.vertices=[];
	this.normals=[];
	this.colors=[];
	this.uvs=[];
	
	this.geometry={
		vertices: [],
		normals: [],
		colors: [],
		uvs: [],
		indices:[],
	}
	this.init();
}

VFG.CalculatorBillboard.prototype.init=function(){
	this.read();
}

/**
 * read
 */
VFG.CalculatorBillboard.prototype.read=function(){
	var _this=this;
	var request = new XMLHttpRequest();
	request.onreadystatechange = function() {
		if (request.readyState == 4 && request.status != 404) {
			try{
				_this.parse(request.responseText);
				_this.create(_this.geometry);
				if(_this.success){
					_this.success(_this);
				}
				if(_this.complete){
					_this.complete();
				}
			}catch (e) {
				if(_this.error){
					_this.error(e);
				}
				if(_this.complete){
					_this.complete();
				}
			}
		}
	};
	request.onerror=function(error){
		if(_this.error){
			_this.error(error);
		}
		if(_this.complete){
			_this.complete();
		}
	};
	request.ontimeout=function(error){
		if(_this.error){
			_this.error('加载超时！');
		}
		if(_this.complete){
			_this.complete();
		}
	};
	request.open('GET', _this.model.url, true); 
	request.send();
	if(_this.complete){
		_this.complete();
	}
}

/**
 * 创建图元
 */
VFG.CalculatorBillboard.prototype.create=function(geometry){
	var _this=this;
	var normals=geometry.normals;
	var uvs=geometry.uvs;
	var vertices=geometry.vertices;
	var indices=new Uint16Array(geometry.indices);
	
/*	this._primitiveYZ=new Cesium.Primitive({
        geometryInstances : new Cesium.GeometryInstance({
            geometry : new Cesium.PlaneGeometry({
                vertexFormat : Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,
            }),
            modelMatrix : this.getModelMatrixYZ(),
            id:_this.id+"-YZ",
            pickPrimitive : this,
            attributes : {
                color : new Cesium.ColorGeometryInstanceAttribute(1.0, 0.0, 0.0, 0.3)
            }
        }),
        appearance : new Cesium.PerInstanceColorAppearance({
            closed: false,
            translucent: false
        })
    })*/

	
	
    this.primitive=_this.viewer.scene.primitives.add(new Cesium.Primitive({
        geometryInstances: new Cesium.GeometryInstance({
            geometry: new Cesium.Geometry({
                attributes: {
                    position: new Cesium.GeometryAttribute({
                        componentDatatype: Cesium.ComponentDatatype.DOUBLE,
                        componentsPerAttribute: 3,
                        values: vertices
                    }),
                    normal: new Cesium.GeometryAttribute({
                        componentDatatype: Cesium.ComponentDatatype.FLOAT,
                        componentsPerAttribute: 3,
                        values: normals
                    }),
                    st: new Cesium.GeometryAttribute({
                        componentDatatype: Cesium.ComponentDatatype.FLOAT,
                        componentsPerAttribute: 2,
                        values: uvs
                    }),
                },
               // indices: indices, 
                pickPrimitive : this,
                primitiveType: Cesium.PrimitiveType.TRIANGLES,
                boundingSphere: Cesium.BoundingSphere.fromVertices(vertices),
            }),
            id : _this.id,
            modelMatrix: _this.getMatrix(),
        }),
       appearance: new Cesium.MaterialAppearance({
    	    material: _this.getMaterial(),
            faceForward : true, 
            closed: false 
        }),
        asynchronous: false
    }));
}

VFG.CalculatorBillboard.prototype.getMaterial = function() {
	var _self = this;
	if(_self.videoEle){
		_self.canplaythrough=function () {
	    	_self.viewer.clock.onTick.addEventListener(_self.activeVideoListener, _self);
	    };
	    _self.videoEle.addEventListener("canplaythrough",_self.canplaythrough);
	    let material = Cesium.Material.fromType('Image');
	    material.uniforms.image =_self.videoEle;
	    return material;
	}
	else if(('0'== _self.model.videoType && _self.model.videoUrl ) || 
			('1'== _self.model.videoType && ( _self.model.videoUrl  ||  _self.model.videoId ) ) ){
		_self.videoEle=_self.createVideoEle();
		_self.isCreateVideoEle=true;
		_self.canplaythrough=function () {
	    	_self.viewer.clock.onTick.addEventListener(_self.activeVideoListener, _self);
	    };
	    _self.videoEle.addEventListener("canplaythrough",_self.canplaythrough );
	    let material = Cesium.Material.fromType('Image');
	    material.uniforms.image =_self.videoEle;
	    return material;
	}
	
	
	else{
		if(_self.model.thumbnail){
			return new Cesium.Material({ 
				fabric : {
	     		    type : 'Image',
	     		    uniforms : {
	     		      image : _self.model.thumbnail
	     		    }
	     		}
	  		})
		}else{
			return new Cesium.Material({
			    fabric : {
			        type : 'Color',
			        uniforms : {
			            color : Cesium.Color.BLACK.withAlpha(0.5)
			        }
			    }
			})
		}
	}
};

VFG.CalculatorBillboard.prototype.createVideoEle = function () {
	var _self = this;
	 var r = document.createElement("VIDEO");
	var src;
	if('0'==_self.model.videoType){
		src=_self.model.videoUrl;
	}
	else{
    	_self.webRtcServer= new WebRtcStreamer(r,_self.model.webRTCUrl);
	    _self.webRtcServer.connect(_self.model.videoId,'','');
	}
	this.videoId = "visualDomId"+_self.option.id;
    var t = document.createElement("SOURCE");
    t.type = "video/mp4",
    t.src = src;
    var i = document.createElement("SOURCE");
    i.type = "video/quicktime",
    i.src = src;
    return r.setAttribute("autoplay", !0),
    r.setAttribute("loop", !0),
    r.setAttribute("crossorigin", !0),
    r.setAttribute("muted", "muted"),
    r.appendChild(t),
    r.appendChild(i),
    r.style.display = "none",
    document.body.appendChild(r),
    r
}

VFG.CalculatorBillboard.prototype.getMatrix = function() {
	var _this = this;
	var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Cartesian3.fromDegrees(this.position.x*1, this.position.y*1,this.position.z*1));
	var scaleMatrix = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(_this.model.scaleX?_this.model.scaleX*1:1,_this.model.scaleY?_this.model.scaleY*1:1,_this.model.scaleZ?_this.model.scaleZ*1:1));
		modelMatrix = Cesium.Matrix4.multiply(modelMatrix, scaleMatrix, new Cesium.Matrix4());
		var hprRotation = Cesium.Matrix3.fromHeadingPitchRoll(new Cesium.HeadingPitchRoll(
				Cesium.Math.toRadians(this.orientation.heading || 0), 
				Cesium.Math.toRadians(this.orientation.pitch || 0), 
				Cesium.Math.toRadians(this.orientation.roll || 0)));
	var hpr = Cesium.Matrix4.fromRotationTranslation(hprRotation,new Cesium.Cartesian3(0.0, 0.0, 0.0));
	return Cesium.Matrix4.multiply(modelMatrix, hpr, modelMatrix);
}; 

VFG.CalculatorBillboard.prototype.activeVideoListener = function (e) {
	var _this=this;
    try {
        if (_this._videoPlay && _this.videoEle.paused) _this.videoEle.play();
    } catch (e) {}
}

VFG.CalculatorBillboard.prototype.deActiveVideo = function (e) {
	this.viewer.clock.onTick.removeEventListener(this.activeVideoListener, this);
}


VFG.CalculatorBillboard.prototype.update=function(param){
	if(param.position){
		this.position=param.position;
	}
	if(param.orientation){
		if(this.orientation.pitch){
			this.orientation.pitch=param.orientation.pitch;
		}
		if(this.orientation.heading){
			this.orientation.heading=param.orientation.heading;
		}
		if(this.orientation.roll){
			this.orientation.roll=param.orientation.roll;
		}
	}
	if(param.scale){
		if(this.scale.x){
			this.model.scaleX=param.scale.x;
		}
		if(this.scale.y){
			this.model.scaleY=param.scale.y;
		}
		if(this.scale.z){
			this.model.scaleZ=param.scale.z;
		}
	}
	if(this.primitive){
		this.primitive.modelMatrix=this.getMatrix();
	}
}

VFG.TModel.prototype.updateThing=function(thing){
	if(thing){
	}
}

VFG.CalculatorBillboard.prototype.addListener=function(type,callback){
	if('success'==type){
		this.success=callback;
	}
	if('error'==type){
		this.error=callback;
	}
	if('complete'==type){
		this.complete=callback;
	}
}

VFG.CalculatorBillboard.prototype.removeListener=function(type){
	if('beforeSend'==type){
		this.beforeSend=null;
	}
	if('success'==type){
		this.success=null;
	}
	if('error'==type){
		this.error=null;
	}
	if('complete'==type){
		this.complete=null;
	}
}

VFG.CalculatorBillboard.prototype.destroy = function () {
  this.deActiveVideo();
  if(this.primitive){
	  this.viewer.scene.primitives.remove(this.primitive);
  }
  if(this.primitive){
	  this.viewer.scene.primitives.remove(this.primitive);
  }
  if(this.videoEle){
	  this.videoEle.removeEventListener('canplaythrough',this.canplaythrough);
  }
  if(this.webRtcServer){
	  this.webRtcServer.disconnect();
  }
  if(this.isCreateVideoEle){
	  this.videoEle && this.videoEle.parentNode.removeChild(this.videoEle);
  }
  delete this.webRtcServer,
  delete this.videoEle,
  delete this.options,
  delete this.model,
  delete this.primitive,
  delete this.viewer;
  return Cesium.destroyObject(this);
};

/*************************************obj模型解析*******************************************/
VFG.CalculatorBillboard.prototype.parse=function( text ) {
	var _this=this;
	if ( text.indexOf( '\r\n' ) !== - 1 ) {
		text = text.replace( /\r\n/g, '\n' );
	}

	if ( text.indexOf( '\\\n' ) !== - 1 ) {
		text = text.replace( /\\\n/g, '' );
	}

	var lines = text.split( '\n' );
	var line = '', lineFirstChar = '';
	var lineLength = 0;
	var result = [];

	// Faster to just trim left side of the line. Use if available.
	var trimLeft = ( typeof ''.trimLeft === 'function' );

	for ( var i = 0, l = lines.length; i < l; i ++ ) {

		line = lines[ i ];
		line = trimLeft ? line.trimLeft() : line.trim();
		lineLength = line.length;
		if ( lineLength === 0 ) continue;

		lineFirstChar = line.charAt( 0 );
		// @todo invoke passed in handler if any
		if ( lineFirstChar === '#' ) continue;

		if ( lineFirstChar === 'v' ) {
			var data = line.split( /\s+/ );
			switch ( data[ 0 ] ) {
				case 'v':
					_this.vertices.push(
						parseFloat( data[ 1 ] ),
						parseFloat( data[ 2 ] ),
						parseFloat( data[ 3 ] )
					);
					if ( data.length >= 7 ) {
						_this.colors.push(
							parseFloat( data[ 4 ] ),
							parseFloat( data[ 5 ] ),
							parseFloat( data[ 6 ] )
						);
					} else {
						_this.colors.push( undefined, undefined, undefined );
					}
					break;
				case 'vn':
					_this.normals.push(
						parseFloat( data[ 1 ] ),
						parseFloat( data[ 2 ] ),
						parseFloat( data[ 3 ] )
					);
					break;
				case 'vt':
					_this.uvs.push(
						parseFloat( data[ 1 ] ),
						parseFloat( data[ 2 ] )
					);
					break;

			}

		} else if ( lineFirstChar === 'f' ) {
			var lineData = line.substr( 1 ).trim();
			var vertexData = lineData.split( /\s+/ );
			var faceVertices = [];

			// Parse the face vertex data into an easy to work with format
			for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
				var vertex = vertexData[ j ];
				if ( vertex.length > 0 ) {
					var vertexParts = vertex.split( '/' );
					faceVertices.push( vertexParts );
					this.geometry.indices.push(vertexParts[0]*1-1);
				}
				
			}
			var v1 = faceVertices[ 0 ];
			for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
				var v2 = faceVertices[ j ];
				var v3 = faceVertices[ j + 1 ];
				_this.addFace(
					v1[ 0 ], v2[ 0 ], v3[ 0 ],
					v1[ 1 ], v2[ 1 ], v3[ 1 ],
					v1[ 2 ], v2[ 2 ], v3[ 2 ]
				);
			}
		} else {
			if ( line === '\0' ) continue;
		}
	}
}

VFG.CalculatorBillboard.prototype.addFace= function ( a, b, c, ua, ub, uc, na, nb, nc ) {
	var vLen = this.vertices.length;
	
	var ia = this.parseVertexIndex( a, vLen );
	var ib = this.parseVertexIndex( b, vLen );
	var ic = this.parseVertexIndex( c, vLen );

	this.addVertex( ia, ib, ic );
	this.addColor( ia, ib, ic );
	
	
	 this.geometry.indices.push(ia);
	 this.geometry.indices.push(ib);
	 this.geometry.indices.push(ic);
	

	// normals
	if ( na !== undefined && na !== '' ) {
		var nLen = this.normals.length;
		ia = this.parseNormalIndex( na, nLen );
		ib = this.parseNormalIndex( nb, nLen );
		ic = this.parseNormalIndex( nc, nLen );
		this.addNormal( ia, ib, ic );
	} else {
		this.addFaceNormal( ia, ib, ic );
	}

	// uvs
	if ( ua !== undefined && ua !== '' ) {
		var uvLen = this.uvs.length;
		ia = this.parseUVIndex( ua, uvLen );
		ib = this.parseUVIndex( ub, uvLen );
		ic = this.parseUVIndex( uc, uvLen );
		this.addUV( ia, ib, ic );
	} else {
		this.addDefaultUV();
	}
}

//use
VFG.CalculatorBillboard.prototype.addVertex=function ( a, b, c ) {
	var src = this.vertices;
	var dst = this.geometry.vertices;
	dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
	dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
	dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
}

//use
VFG.CalculatorBillboard.prototype.addNormal=function ( a, b, c ) {
	var src = this.normals;
	var dst = this.geometry.normals;
	dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
	dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
	dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
}

//use
VFG.CalculatorBillboard.prototype.addFaceNormal=function ( a, b, c ) {

	var src = this.vertices;
	var dst = this.geometry.normals;

	vA.fromArray( src, a );
	vB.fromArray( src, b );
	vC.fromArray( src, c );

	cb.subVectors( vC, vB );
	ab.subVectors( vA, vB );
	cb.cross( ab );

	cb.normalize();

	dst.push( cb.x, cb.y, cb.z );
	dst.push( cb.x, cb.y, cb.z );
	dst.push( cb.x, cb.y, cb.z );

}

//use
VFG.CalculatorBillboard.prototype.addColor= function ( a, b, c ) {

	var src = this.colors;
	var dst = this.geometry.colors;

	if ( src[ a ] !== undefined ) dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
	if ( src[ b ] !== undefined ) dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
	if ( src[ c ] !== undefined ) dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );

}

//use
VFG.CalculatorBillboard.prototype.addUV= function ( a, b, c ) {
	var src = this.uvs;
	var dst = this.geometry.uvs;
	dst.push( src[ a + 0 ], src[ a + 1 ] );
	dst.push( src[ b + 0 ], src[ b + 1 ] );
	dst.push( src[ c + 0 ], src[ c + 1 ] );
}

//use
VFG.CalculatorBillboard.prototype.addDefaultUV=function () {
	var dst = this.geometry.uvs;
	dst.push( 0, 0 );
	dst.push( 0, 0 );
	dst.push( 0, 0 );
}

VFG.CalculatorBillboard.prototype.parseVertexIndex=function ( value, len ) {
	var index = parseInt( value, 10 );
	return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
}

VFG.CalculatorBillboard.prototype.parseNormalIndex=function ( value, len ) {
	var index = parseInt( value, 10 );
	return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
}
VFG.CalculatorBillboard.prototype.parseUVIndex=function ( value, len ) {
	var index = parseInt( value, 10 );
	return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
}


;
///<jscompress sourcefile="CommonImageryProvider.js" />
VFG.CommonImageryProvider = function(viewer, options) {
	this.viewer = viewer;
	this.options = options;
	this.id = options.id;
	this.name = options.name;
	this.code = options.code;
	this.type = options.type;
	this.imagery = options.thing;
	this.init();
}

//初始化
VFG.CommonImageryProvider.prototype.init = function() {
	let provider;
	if('terrain'==this.imagery.classify){
		provider=this.getTerrain();
		if(provider) this.ImageryProvider=this.viewer.terrainProvider = provider;
	}else{
		if('url'==this.imagery.serverType){
			provider=this.getUrlTemplateImageryProvider();
			if(provider) this.ImageryProvider=this.viewer.imageryLayers.addImageryProvider(provider);
		}
		else if('wmts'==this.imagery.serverType){
			provider=this.getWebMapTileServiceImageryProvider();
			if(provider) this.ImageryProvider=this.viewer.imageryLayers.addImageryProvider(provider);
		}
		else if('tms'==this.imagery.serverType){
			provider=this.getTileMapServiceImageryProvider();
			if(provider) this.ImageryProvider=this.viewer.imageryLayers.addImageryProvider(provider);
		}
	}
};

VFG.CommonImageryProvider.prototype.getUrlTemplateImageryProvider = function() {
	var parameter=eval('(' + this.imagery.options + ')') ;
	return new Cesium.UrlTemplateImageryProvider(parameter);
};

VFG.CommonImageryProvider.prototype.getTerrain = function() {
	var parameter=eval('(' + this.imagery.options + ')') ;
	return new Cesium.CesiumTerrainProvider(parameter)
};

VFG.CommonImageryProvider.prototype.getWebMapTileServiceImageryProvider = function() {
	return new Cesium.WebMapTileServiceImageryProvider(this.imagery.options)
};

VFG.CommonImageryProvider.prototype.getTileMapServiceImageryProvider = function() {
	return new Cesium.TileMapServiceImageryProvider(this.imagery.options)
};

VFG.CommonImageryProvider.prototype.destroy = function() {
	if(this.ImageryProvider){
		if('terrain'!=this.imagery.classify){
			this.viewer.imageryLayers.remove(this.ImageryProvider);
		}else{
			this.viewer.terrainProvider= new Cesium.EllipsoidTerrainProvider({});
		}
	}
	delete this.ImageryProvider
	delete this.options
    delete this.viewer
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="TiandituImageryProvider.js" />
VFG.TiandituImageryProvider = function(viewer, options) {
	this.viewer = viewer;
	this.options = options;
	this.id = options.id;
	this.name = options.name;
	this.code = options.code;
	this.type = options.type;
	this.imagery = options.thing;
	this.subdomains=['0','1','2','3','4','5','6','7'];
	this.tdtUrl = 'https://t{s}.tianditu.gov.cn/';
	this.init();
}

//初始化
VFG.TiandituImageryProvider.prototype.init = function() {
	let provider;
	if('terrain'==this.imagery.classify){
		provider=this.getTerrain();
		if(provider) this.ImageryProvider=this.viewer.terrainProvider = provider;
	}else{
		if('img_w'==this.imagery.type){
			provider=this.getImg_w();
			if(provider) this.ImageryProvider=this.viewer.imageryLayers.addImageryProvider(provider);
		}
		else if('cia_w'==this.imagery.type){
			provider=this.getCia_w();
			if(provider) this.ImageryProvider=this.viewer.imageryLayers.addImageryProvider(provider);
		}
		else if('ibo_w'==this.imagery.type){
			provider=this.getIbo_w();
			if(provider) this.ImageryProvider=this.viewer.imageryLayers.addImageryProvider(provider);
		}
		else if('ter_w'==this.imagery.type){
			provider=this.getTer_w();
			if(provider) this.ImageryProvider=this.viewer.imageryLayers.addImageryProvider(provider);
		}
		else if('vec_w'==this.imagery.type){
			provider=this.getVec_w();
			if(provider) this.ImageryProvider=this.viewer.imageryLayers.addImageryProvider(provider);
		}
	}
};


//影像底图
VFG.TiandituImageryProvider.prototype.getImg_w = function() {
/*	return new Cesium.WebMapTileServiceImageryProvider({
		url: "http://t{s}.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk="+this.imagery.auth,
	      subdomains: this.subdomains,
	      layer: "tdtImgLayer",
	      style: "default",
	      format: "image/jpeg",
	      tileMatrixSetID: "GoogleMapsCompatible",
	      show: true
	});*/
	return new Cesium.UrlTemplateImageryProvider({
	    url: this.tdtUrl + 'DataServer?T=img_w&x={x}&y={y}&l={z}&tk=' + this.imagery.auth,
	    subdomains: this.subdomains,
	    tilingScheme : new Cesium.WebMercatorTilingScheme(),
	    maximumLevel : 18
	});
};


//影像注记
VFG.TiandituImageryProvider.prototype.getCia_w = function() {
	return new Cesium.UrlTemplateImageryProvider({
	    url: this.tdtUrl + 'DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=' + this.imagery.auth,
	    subdomains: this.subdomains,
	    tilingScheme : new Cesium.WebMercatorTilingScheme(),
	    maximumLevel : 18
	});
	
/*	return new Cesium.WebMapTileServiceImageryProvider({
		url: "http://t{s}.tianditu.com/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg&tk="+this.imagery.auth,
	    subdomains: this.subdomains,
	    layer: "tdtCiaLayer",
	    style: "default",
	    format: "image/jpeg",
	    tileMatrixSetID: "GoogleMapsCompatible",
	    show: true
	});*/
};

//地形晕渲
VFG.TiandituImageryProvider.prototype.getTer_w = function() {
	return new Cesium.UrlTemplateImageryProvider({
	    url: this.tdtUrl + 'DataServer?T=ter_w&x={x}&y={y}&l={z}&tk=' + this.imagery.auth,
	    subdomains: this.subdomains,
	    tilingScheme : new Cesium.WebMercatorTilingScheme(),
	    maximumLevel : 18
	});
};

//矢量
VFG.TiandituImageryProvider.prototype.getVec_w = function() {
	return new Cesium.UrlTemplateImageryProvider({
	    url: this.tdtUrl + 'DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=' + this.imagery.auth,
	    subdomains: this.subdomains,
	    tilingScheme : new Cesium.WebMercatorTilingScheme(),
	    maximumLevel : 18
	});
};

//叠加地形服务
VFG.TiandituImageryProvider.prototype.getTerrain = function() {
	var terrainUrls = new Array();
	for (var i = 0; i < this.subdomains.length; i++){
	    var url = this.tdtUrl.replace('{s}', this.subdomains[i]) + 'mapservice/swdx?tk=' + this.imagery.auth;
	    terrainUrls.push(url);
	}
	return new Cesium.GeoTerrainProvider({
	    urls: terrainUrls
	});
};

//叠加国界服务
VFG.TiandituImageryProvider.prototype.getIbo_w = function() {
	return new Cesium.UrlTemplateImageryProvider({
	    url: this.tdtUrl + 'DataServer?T=ibo_w&x={x}&y={y}&l={z}&tk=' + this.imagery.auth,
	    subdomains: this.subdomains,
	    tilingScheme : new Cesium.WebMercatorTilingScheme(),
	    maximumLevel : 10
	})
};

VFG.TiandituImageryProvider.prototype.destroy = function() {
	if(this.ImageryProvider){
		if('terrain'!=this.imagery.classify){
			this.viewer.imageryLayers.remove(this.ImageryProvider);
		}else{
			this.viewer.terrainProvider= new Cesium.EllipsoidTerrainProvider({});
		}
	}
	delete this.ImageryProvider
	delete this.options
    delete this.viewer
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="EditPModel.js" />
VFG.EditPModel=function(viewer,entity){
	this.viewer=viewer;
	this.tip=new VFG.Tip(viewer);
	this.entity=entity;
	this.position=entity.position||null;
	this.orientation=entity.orientation||{};
	this.model=entity;
	
	this.cartesian3;
	this.rotatePosition;
	this.radius;
	this.init();
}
VFG.EditPModel.prototype.init=function(){
	var _this=this;
	this.cartesian3 = VFG.Util.getLnLaToC3(this.position);
	this.height = Cesium.Cartographic.fromCartesian(this.cartesian3).height;
    this.radius = _this.entity.getRadius();
	_this.ellipseEntity = this.viewer.entities.add({
        position: new Cesium.CallbackProperty(function (time) {
            return _this.cartesian3;
        }, false),
        ellipse:{
            fill: false,
            outline: true,
            outlineColor: Cesium.Color.YELLOW,
            outlineWidth:2,
            semiMajorAxis: new Cesium.CallbackProperty(function (time) {
                return _this.radius;
            }, false),
            semiMinorAxis:new Cesium.CallbackProperty(function (time) {
                return _this.radius;
            }, false),
            height:  new Cesium.CallbackProperty(function (time) {
                return Cesium.Cartographic.fromCartesian(_this.cartesian3).height;
            }, false)
        }
    });
	_this.rotatePosition=this.getHeadingPosition();
	
	_this.rotatePoint=_this.viewer.entities.add({
		id:_this.entity.id+'-rotatePoint',
        position: new Cesium.CallbackProperty(function (time) {
            return _this.rotatePosition;
        }, false),
        point:{
            color: Cesium.Color.VIOLET  ,
            pixelSize:10,
        }
    });
	_this.zoomPoint=_this.viewer.entities.add({
		id:_this.entity.id+'-zoomPoint',
        position: new Cesium.CallbackProperty(function (time) {
            return VFG.Util.addPositionsHeight(_this.cartesian3, _this.radius);
        }, false),
        point:{
            color: Cesium.Color.BLUEVIOLET,
            pixelSize:10,
        }
    }); 
	
	this._handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
	var pickEntity;
	
	//鼠标左键按下
	this._handler.setInputAction(function(e) {
		let pick = _this.viewer.scene.pick(e.position);
		if (Cesium.defined(pick) && Cesium.defined(pick.id) && pick.id.id==_this.entity.id+'-rotatePoint'){
			_this.pickEntity=pick;
	 		_this.rotatePoint.point.color=Cesium.Color.YELLOW;
	 		_this.viewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
		}
		else if (Cesium.defined(pick) && Cesium.defined(pick.id) && pick.id.id==_this.entity.id+'-zoomPoint'){
			_this.pickEntity=pick;
	 		_this.zoomPoint.point.color=Cesium.Color.YELLOW;
	 		_this.viewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
		} 
		else if(Cesium.defined(pick) && Cesium.defined(pick.id)  && pick.id==_this.entity.id){
			_this.pickEntity=pick;
	 		//_this.rotatePoint.point.color=Cesium.Color.YELLOW;
	 		_this.viewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
		}
	},Cesium.ScreenSpaceEventType.LEFT_DOWN);
    
	this._handler.setInputAction(function(e) {
		if(_this.pickEntity){
			if(Cesium.defined(_this.pickEntity.id) && _this.pickEntity.id.id==_this.entity.id+'-rotatePoint'){
				_this.rotatePoint.point.color=Cesium.Color.VIOLET;
			}
			else if(Cesium.defined(_this.pickEntity.id) && _this.pickEntity.id.id==_this.entity.id+'-zoomPoint'){
				_this.zoomPoint.point.color=Cesium.Color.BLUEVIOLET;
			}
		}
		_this.viewer.scene.screenSpaceCameraController.enableRotate = true;
		_this.tip.setVisible(false);
		_this.pickEntity=null;
	},Cesium.ScreenSpaceEventType.LEFT_UP);
	
	this._handler.setInputAction(function(movement) {
		let pick = _this.viewer.scene.pick(movement.endPosition);
		if (Cesium.defined(pick) && Cesium.defined(pick.id) && pick.id.id==_this.entity.id+'-rotatePoint'){
			_this.tip.setVisible(true);
			_this.tip.showAt(movement.endPosition,"按住鼠标左键拖动点调整模型方位角。");
		}
		else if (Cesium.defined(pick) && Cesium.defined(pick.id) && pick.id.id==_this.entity.id+'-zoomPoint'){
			_this.tip.setVisible(true);
			_this.tip.showAt(movement.endPosition,"按住鼠标左键拖动点调整模型缩放。");
		}
		else if(Cesium.defined(pick) && Cesium.defined(pick.id)  && pick.id==_this.entity.id){
			_this.tip.setVisible(true);
			_this.tip.showAt(movement.endPosition,"按住鼠标左键可拖动模型位置。");
		}else{
			_this.tip.setVisible(false);
		}
		
		if(_this.pickEntity){
			let endC3=VFG.Util.getScreenToC3(_this.viewer, movement.endPosition, _this.pickEntity);
			if(Cesium.defined(endC3)){
				if(Cesium.defined(_this.pickEntity.id) && _this.pickEntity.id.id==_this.entity.id+'-rotatePoint'){
					_this.orientation.heading=_this.getHeading(_this.cartesian3, endC3);
					_this.rotatePosition=_this.getHeadingPosition();
					_this.entity.updateHeading(_this.orientation.heading)
					if(_this.change){
						_this.change({
							heading:_this.orientation.heading,
						});
					}
					_this.tip.showAt(movement.endPosition,"调整模型方位角中...");
				}
				else if(Cesium.defined(_this.pickEntity.id) && _this.pickEntity.id.id==_this.entity.id+'-zoomPoint'){
                    var radiusNew = Cesium.Cartesian3.distance(endC3, _this.cartesian3);
                    var radiusOld = _this.radius / (_this.model.model.scale||1)*1;
                    var scaleNew = radiusNew / radiusOld;
                    _this.radius = radiusNew;
                    _this.model.model.scale = VFG.Util.formatNum(scaleNew, 2);
                    _this.entity.updateScale(_this.model.model.scale);
					_this.rotatePosition=_this.getHeadingPosition();
					if(_this.change){
						_this.change({
							scale:_this.model.model.scale,
						});
					}
					_this.tip.showAt(movement.endPosition,"调整模型缩放中...");
				}
				else if(_this.pickEntity.id==_this.entity.id){
					_this.cartesian3=endC3;
					_this.rotatePosition=_this.getHeadingPosition();
					let LnLa=VFG.Util.getLnLaFormC3(_this.viewer, endC3);
					_this.entity.updatePosition(LnLa)
					if(Cesium.defined(LnLa)){
						if(_this.change){
							_this.change({
								position:LnLa,
							});
						}
					}
					_this.tip.showAt(movement.endPosition,"调整模型位置中...");
				}
			}
		}
	}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
	this._handler.setInputAction(function(movement) {
	}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
	
/*	new VFG.OrbitControls(this.viewer,{
		id:this.entity.id,
		position:this.cartesian3,
		scale:this.radius,
		callback:function(position){
			_this.cartesian3=position;
		}
	})*/
}

VFG.EditPModel.prototype.getHeadingPosition=function(){
    var _this=this;
    var angle = -Number(this.orientation.heading || 0);
    var rotpos = new Cesium.Cartesian3(this.radius, 0.0, 0.0);
    var mat = Cesium.Transforms.eastNorthUpToFixedFrame(this.cartesian3);
    var rotationX = Cesium.Matrix4.fromRotationTranslation(Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(angle)));
    Cesium.Matrix4.multiply(mat, rotationX, mat);
    mat = Cesium.Matrix4.getMatrix3(mat, new Cesium.Matrix3());
    rotpos = Cesium.Matrix3.multiplyByVector(mat, rotpos, rotpos);
    rotpos = Cesium.Cartesian3.add(this.cartesian3, rotpos, rotpos);
    return rotpos;
}

VFG.EditPModel.prototype.getHeading=function(positionCenter, positionNew){
    var mat = Cesium.Transforms.eastNorthUpToFixedFrame(positionCenter);
    mat = Cesium.Matrix4.getMatrix3(mat, new Cesium.Matrix3());
    var xaxis = Cesium.Matrix3.getColumn(mat, 0, new Cesium.Cartesian3());
    var yaxis = Cesium.Matrix3.getColumn(mat, 1, new Cesium.Cartesian3());
    var zaxis = Cesium.Matrix3.getColumn(mat, 2, new Cesium.Cartesian3());
    var dir = Cesium.Cartesian3.subtract(positionNew, positionCenter, new Cesium.Cartesian3());
    dir = Cesium.Cartesian3.cross(dir, zaxis, dir);
    dir = Cesium.Cartesian3.cross(zaxis, dir, dir);
    dir = Cesium.Cartesian3.normalize(dir, dir);
    var heading = Cesium.Cartesian3.angleBetween(xaxis, dir);
    var ay = Cesium.Cartesian3.angleBetween(yaxis, dir);
    if (ay > Math.PI * 0.5) {
        heading = 2 * Math.PI - heading;
    }
    return -Cesium.Math.toDegrees(heading);
}

VFG.EditPModel.prototype.on = function(type,callback) {
	if('change'==type){
		this.change=callback;
	}
};

VFG.EditPModel.prototype.update=function(entity){
    var _this=this;
    if(entity){
    	
    	_this.entity=entity;
    	_this.position=entity.position||null;
    	_this.orientation=entity.orientation||{};
    	_this.model=entity;
    	
    	_this.cartesian3 = VFG.Util.getLnLaToC3(_this.position);
    	_this.height = Cesium.Cartographic.fromCartesian(_this.cartesian3).height;
    	_this.radius = _this.entity.getRadius();
    	_this.rotatePosition=_this.getHeadingPosition();
    	
    }
}


VFG.EditPModel.prototype.destroy = function() {
    if(this.ellipseEntity){
    	this.viewer.entities.remove(this.ellipseEntity);
    }
    if(this.rotatePoint){
    	this.viewer.entities.remove(this.rotatePoint);
    }
    if(this.zoomPoint){
    	this.viewer.entities.remove(this.zoomPoint);
    }
    if( this._handler){
    	this._handler.destroy();
    	this._handler = null;
    };
    if(this.tip){
    	this.tip.destroy();
    }
	delete this.ellipseEntity;
	delete this.rotatePoint;
	delete this.zoomPoint;
    delete this.viewer;
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="EditTModel.js" />
VFG.EditTModel=function(viewer,entity){
	this.viewer=viewer;
	this.tip=new VFG.Tip(viewer);
	this.entity=entity;
	this.position=entity.position||null;
	this.orientation=entity.orientation||{};
	this.model=entity;
	this.cartesian3;
	this.radius;
	this.init();
}
VFG.EditTModel.prototype.init=function(){
	var _this=this;
	this.radius = _this.entity.getRadius()/5;
	this.cartesian3 = Cesium.Cartesian3.fromDegrees(this.position.x*1, this.position.y*1,this.position.z*1+this.radius);
	this.orbitControls=new VFG.OrbitControls(this.viewer,{
		id:this.entity.id,
		position:this.cartesian3,
		scale:this.radius,
		callback:function(position){
			_this.cartesian3=position;
			let LnLa = VFG.Util.getLnLaFormC3(_this.viewer, position);
			if (Cesium.defined(LnLa)) {
				let new_position={
					x:LnLa.x,
					y:LnLa.y,
					z:LnLa.z*1-_this.radius,
				};
				if(_this.change){
					_this.change({
						position:new_position
					});
				}
				if(_this.entity){
					_this.entity.update({
						position:new_position
					});
				}
			}
		}
	})
}


VFG.EditTModel.prototype.on = function(type,callback) {
	if('change'==type){
		this.change=callback;
	}
};

VFG.EditTModel.prototype.update=function(entity){
    var _this=this;
    if(entity){
    }
}


VFG.EditTModel.prototype.destroy = function() {
    if(this.orbitControls){
    	this.orbitControls.destroy();
    }
    if( this._handler){
    	this._handler.destroy();
    	this._handler = null;
    };
    if(this.tip){
    	this.tip.destroy();
    }
	delete this.orbitControls;
    delete this.viewer;
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="EditVModel.js" />
VFG.EditVModel=function(viewer,entity){
	this.viewer=viewer;
	this.tip=new VFG.Tip(viewer);
	this.entity=entity;
	this.position=entity.position||null;
	this.orientation=entity.orientation||{};
	this.model=entity;
	this.cartesian3;
	this.radius;
	this.init();
}

VFG.EditVModel.prototype.init=function(){
	var _this=this;
	this.cartesian3 = Cesium.Cartesian3.fromDegrees(this.position.x*1, this.position.y*1,this.position.z*1+1);
	this.radius = _this.entity.getRadius();
	this.orbitControls=new VFG.OrbitControls(this.viewer,{
		id:this.entity.id,
		position:this.cartesian3,
		scale:15,
		callback:function(position){
			_this.cartesian3=position;
			let LnLa = VFG.Util.getLnLaFormC3(_this.viewer, position);
			if (Cesium.defined(LnLa)) {
				let new_position={
					x:LnLa.x,
					y:LnLa.y,
					z:LnLa.z*1-1,
				};
				if(_this.change){
					_this.change({
						position:new_position
					});
				}
				if(_this.entity){
					_this.entity.update({
						position:new_position
					});
				}
			}
		}
	})
}


VFG.EditVModel.prototype.on = function(type,callback) {
	if('change'==type){
		this.change=callback;
	}
};

VFG.EditVModel.prototype.update=function(entity){
    var _this=this;
    if(entity){
    	
/*    	_this.entity=entity;
    	_this.position=entity.position||null;
    	_this.orientation=entity.orientation||{};
    	_this.model=entity;
    	
    	_this.cartesian3 = VFG.Util.getLnLaToC3(_this.position);
    	_this.height = Cesium.Cartographic.fromCartesian(_this.cartesian3).height;
    	_this.radius = _this.entity.getRadius();
    	_this.rotatePosition=_this.getHeadingPosition();*/
    	
    }
}


VFG.EditVModel.prototype.destroy = function() {
    if(this.orbitControls){
    	this.orbitControls.destroy();
    }
    if( this._handler){
    	this._handler.destroy();
    	this._handler = null;
    };
    if(this.tip){
    	this.tip.destroy();
    }
	delete this.orbitControls;
    delete this.viewer;
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="DrawPModel.js" />
VFG.DrawPModel=function(viewer,option){
	this.viewer=viewer;
	this.option=option;
	this.id=option.id;
	this.model=option.thing;
	this.position=null;
	this.tip=new VFG.Tip(viewer);
	this.loading=false;
	this.loadingError=true;
	this.entity;
	this.init();
}

VFG.DrawPModel.prototype.init = function() {
	var _this=this;
	this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
	this.handler.setInputAction(function (movement) {
		if(_this.success && !_this.loadingError){
			_this.success(_this.position);
		}else{
			if(_this.error){
				_this.error();
			}
		}
		_this.destroy();
    },Cesium.ScreenSpaceEventType.LEFT_CLICK)
    
    this.handler.setInputAction(function (movement) {
    	if(_this.loading){
    		_this.tip.showAt(movement.endPosition,"加载模型中...");
    	}else{
    		if(_this.loadingError){
    			_this.tip.showAt(movement.endPosition,"模型加载失败，右键退出");
    		}else{
    			_this.tip.showAt(movement.endPosition,"单击完成绘制，右键取消！");
    		}
    	}
    	let position=VFG.Util.getScreenToLnLa(_this.viewer, movement.endPosition, _this.entity);
    	if (Cesium.defined(position)){
    		_this.position=position;
    		_this.render(position);
    	}
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
	this.handler.setInputAction(function (movement) {
		if (Cesium.defined(_this.entity)){
			_this.entity.destroy();
		}
		if(_this.error){
			_this.error();
		}
		_this.destroy();
	}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
};

VFG.DrawPModel.prototype.render = function(position) {
	var _this=this;
	if (!Cesium.defined(this.entity) && this.loading==false){
		this.loading=true;
		this.option.position=position;
		this.entity=new VFG.PModel(_this.viewer,this.option)
		this.entity.on("beforeSend",function(e){
		});
		this.entity.on("success",function(e){
			_this.loading=false;
			_this.loadingError= false;
		});
		this.entity.on("error",function(e){
			_this.loading=false;
			_this.loadingError=true;
		});
		this.entity.on("complete",function(e){
		});
	}
	if (Cesium.defined(this.entity) && this.loading==false && !this.loadingError){
		this.option.position=position;
		this.entity.updatePosition(position);
	}
};

VFG.DrawPModel.prototype.on = function(type,callback) {
	var _this=this;
	if("error"==type){
		this.error=callback;
	}
	if("success"==type){
		this.success=callback;
	}
	if("complete"==type){
		this.complete=callback;
	}
};


VFG.DrawPModel.prototype.destroy = function() {
	
	if(this.complete){
		this.complete();
	}
	
    if( this.handler){
    	this.handler.destroy();
    	this.handler = null;
    };
    if(this.tip){
    	this.tip.destroy();
    }
	if(this.entity.destroy){
		this.entity.destroy();
	}
	delete this.entity;
	delete this.option;
    delete this.viewer;
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="DrawVModel.js" />
VFG.DrawVModel=function(viewer,option){
	this.viewer=viewer;
	this.option=option;
	this.id=option.id;
	this.model=option.thing;
	this.position=null;
	this.tip=new VFG.Tip(viewer);
	this.loading=false;
	this.loadingError=true;
	this.entity;
	this.init();
}

VFG.DrawVModel.prototype.init = function() {
	var _this=this;
	this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
	this.handler.setInputAction(function (movement) {
		if(_this.success && !_this.loadingError){
			_this.success(_this.position);
		}else{
			if(_this.error){
				_this.error();
			}
		}
		_this.destroy();
    },Cesium.ScreenSpaceEventType.LEFT_CLICK)
    
    this.handler.setInputAction(function (movement) {
    	if(_this.loading){
    		_this.tip.showAt(movement.endPosition,"加载模型中...");
    	}else{
    		if(_this.loadingError){
    			_this.tip.showAt(movement.endPosition,"模型加载失败，右键退出");
    		}else{
    			_this.tip.showAt(movement.endPosition,"单击完成绘制，右键取消！");
    		}
    	}
    	let position=VFG.Util.getScreenToLnLa(_this.viewer, movement.endPosition, _this.entity);
    	if (Cesium.defined(position)){
    		_this.position=position;
    		_this.render(position);
    	}
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
	this.handler.setInputAction(function (movement) {
		if (Cesium.defined(_this.entity)){
			_this.entity.destroy();
		}
		if(_this.error){
			_this.error();
		}
		_this.destroy();
	}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
};

VFG.DrawVModel.prototype.render = function(position) {
	var _this=this;
	if (!Cesium.defined(this.entity) && this.loading==false){
		this.loading=true;
		this.option.position=position;
		this.entity=VFG.Render.getVModel(_this.viewer,this.option,this.option.uri);
		this.entity.addListener("beforeSend",function(e){
		});
		this.entity.addListener("success",function(e){
			_this.loading=false;
			_this.loadingError= false;
			console.log(e);
		});
		this.entity.addListener("error",function(e){
			_this.loading=false;
			_this.loadingError=true;
			console.log(e);
		});
		this.entity.addListener("complete",function(e){
		});
	}
	if (Cesium.defined(this.entity) && this.loading==false && !this.loadingError){
		this.option.position=position;
		this.entity.update({
			position:position
		});
	}
};

VFG.DrawVModel.prototype.on = function(type,callback) {
	var _this=this;
	if("error"==type){
		this.error=callback;
	}
	if("success"==type){
		this.success=callback;
	}
	if("complete"==type){
		this.complete=callback;
	}
};

VFG.DrawVModel.prototype.destroy = function() {
	if(this.complete){
		this.complete();
	}
    if( this.handler){
    	this.handler.destroy();
    	this.handler = null;
    };
    if(this.tip){
    	this.tip.destroy();
    }
	if(this.entity){
		this.entity.destroy();
	}
	delete this.entity;
    delete this.viewer;
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="OrbitControls.js" />
VFG.OrbitControls=function(viewer,options){
	this.viewer=viewer;
	this.options=options;
	this.id=options.id;
	this.position=this.options.position;
	this.scale=this.options.scale||1;
	this.modelMatrix=Cesium.Transforms.eastNorthUpToFixedFrame(this.options.position);
	this.pickRay = new Cesium.Ray();
	this._init();
}

VFG.OrbitControls.prototype._init = function() {
	var _this=this;
	
    // 向上的向量
    const vectorNormalUp = new Cesium.Cartesian3()
    const vZ = new Cesium.Cartesian3(0, 0, 1)
    Cesium.Cartesian3.normalize(this.position.clone(), vectorNormalUp)

    // 向右的向量
    const vectorNormalRight = new Cesium.Cartesian3()
    // 由z轴向上 地表向上两个向量叉乘, 则可以得出, 向右的向量
    Cesium.Cartesian3.cross(vZ, vectorNormalUp, vectorNormalRight)

    // 向前的向量
    const vectorNormalFront = new Cesium.Cartesian3()
    Cesium.Cartesian3.cross(vectorNormalRight, vectorNormalUp, vectorNormalFront)
    Cesium.Cartesian3.multiplyByScalar(vectorNormalFront, -1, vectorNormalFront)
    
    
    this.axisX = {
        id: 'axisX',
        color: Cesium.Color.GREEN,
        direction: vectorNormalRight,
        unit: Cesium.Cartesian3.UNIT_X,
    }
    this.axisZ ={
        id: 'axisZ',
        color: Cesium.Color.RED,
        direction: vectorNormalUp,
        unit: Cesium.Cartesian3.UNIT_Z,
    }
    this.axisY ={
        id: 'axisY',
        color: Cesium.Color.BLUE,
        direction: vectorNormalFront,
        unit: Cesium.Cartesian3.UNIT_Y,
    }
	
    this._primitiveX=new Cesium.Primitive({
        geometryInstances : new  Cesium.GeometryInstance({
            geometry : new  Cesium.PolylineGeometry({
                positions : [
                	 Cesium.Cartesian3.ZERO,
                	 Cesium.Cartesian3.UNIT_X
                ],
                width :16,
                vertexFormat : Cesium.PolylineMaterialAppearance.VERTEX_FORMAT,
                colors : [
                	 Cesium.Color.RED,
                	 Cesium.Color.RED
                ],
                arcType:  Cesium.ArcType.NONE
            }),
            id:_this.id+"-X", 
            modelMatrix :_this.getModelMatrix(),
            pickPrimitive : this
        }),
        appearance : new Cesium.PolylineMaterialAppearance({
            material : new Cesium.Material({
                fabric : {
                    type : 'PolylineArrow',
                    uniforms : {
                        color :  Cesium.Color.RED
                    }
                }
            })
        })
    })
    
    
    this._primitiveY=new Cesium.Primitive({
        geometryInstances : new  Cesium.GeometryInstance({
            geometry : new  Cesium.PolylineGeometry({
                positions : [
                	Cesium.Cartesian3.ZERO,
                	Cesium.Cartesian3.UNIT_Y
                ],
                width :16,
                vertexFormat : Cesium.PolylineMaterialAppearance.VERTEX_FORMAT,
                colors : [
                	 Cesium.Color.GREEN,
                	 Cesium.Color.GREEN
                ],
                arcType:  Cesium.ArcType.NONE
            }),
            id:_this.id+"-Y",
            modelMatrix :_this.getModelMatrix(),
            pickPrimitive : this
        }),
        appearance : new Cesium.PolylineMaterialAppearance({
            material : new Cesium.Material({
                fabric : {
                    type : 'PolylineArrow',
                    uniforms : {
                        color :  Cesium.Color.GREEN
                    }
                }
            })
        })
    })
    
    this._primitiveZ=new Cesium.Primitive({
        geometryInstances : new  Cesium.GeometryInstance({
            geometry : new  Cesium.PolylineGeometry({
                positions : [
                	 Cesium.Cartesian3.ZERO,
                	 Cesium. Cartesian3.UNIT_Z
                ],
                width :16,
                vertexFormat : Cesium.PolylineMaterialAppearance.VERTEX_FORMAT,
                colors : [
                	 Cesium.Color.BLUE,
                	 Cesium.Color.BLUE
                ],
                arcType:  Cesium.ArcType.NONE
            }),
            id:_this.id+"-Z",
            modelMatrix :_this.getModelMatrix(),
            pickPrimitive : this
        }),
        appearance : new Cesium.PolylineMaterialAppearance({
            material : new Cesium.Material({
                fabric : {
                    type : 'PolylineArrow',
                    uniforms : {
                        color :  Cesium.Color.BLUE
                    }
                }
            })
        })
    })
    
    //xy面
	this._primitiveXY=new Cesium.Primitive({
        geometryInstances : new Cesium.GeometryInstance({
            geometry : new Cesium.PlaneGeometry({
                vertexFormat : Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,
            }),
            modelMatrix : this.getModelMatrixXY(),
            id:_this.id+"-XY",
            pickPrimitive : this,
            attributes : {
                color : Cesium.ColorGeometryInstanceAttribute.fromColor(new Cesium.Color(1.0, 0.0, 0.0, 0.3))
            }
        }),
        appearance : new Cesium.PerInstanceColorAppearance({
            closed: false,
            translucent: false
        })
    })
    
    
    //xz面
	this._primitiveXZ=new Cesium.Primitive({
        geometryInstances : new Cesium.GeometryInstance({
            geometry : new Cesium.PlaneGeometry({
                vertexFormat : Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,
            }),
            modelMatrix : this.getModelMatrixXZ(),
            id:_this.id+"-XZ",
            pickPrimitive : this,
            attributes : {
                color : Cesium.ColorGeometryInstanceAttribute.fromColor(new Cesium.Color(1.0, 0.0, 0.0, 0.3))
            }
        }),
        appearance : new Cesium.PerInstanceColorAppearance({
            closed: false,
            translucent: false
        })
    })
	
    //yz
	this._primitiveYZ=new Cesium.Primitive({
        geometryInstances : new Cesium.GeometryInstance({
            geometry : new Cesium.PlaneGeometry({
                vertexFormat : Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,
            }),
            modelMatrix : this.getModelMatrixYZ(),
            id:_this.id+"-YZ",
            pickPrimitive : this,
            attributes : {
                color : new Cesium.ColorGeometryInstanceAttribute(1.0, 0.0, 0.0, 0.3)
            }
        }),
        appearance : new Cesium.PerInstanceColorAppearance({
            closed: false,
            translucent: false
        })
    })

    this.viewer.scene.primitives.add( this._primitiveX );
    this.viewer.scene.primitives.add( this._primitiveY );
    this.viewer.scene.primitives.add( this._primitiveZ );
    this.viewer.scene.primitives.add(this._primitiveXY);
    this.viewer.scene.primitives.add(this._primitiveXZ);
    this.viewer.scene.primitives.add(this._primitiveYZ);
    
	this._handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
	var selectedAxis;
	
	//鼠标左键按下
	this._handler.setInputAction(function(e) {
		var pick = _this.viewer.scene.pick(e.position);
		if (Cesium.defined(pick) && pick.id && (  pick.id==_this.id+"-Z" ||   pick.id==_this.id+"-X" ||  pick.id==_this.id+"-Y" ||  pick.id==_this.id+"-XY" ||  pick.id==_this.id+"-XZ" ||  pick.id==_this.id+"-YZ" )){
			_this.pickPoint = _this.viewer.scene.pickPosition(e.position);
			selectedAxis=pick;
			if(pick.id==_this.id+"-X"){
		 		_this._primitiveX.appearance.material.uniforms.color=Cesium.Color.YELLOW;
		 		_this.viewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
		 	}
		 	else if(pick.id==_this.id+"-Y"){
		 		_this._primitiveY.appearance.material.uniforms.color=Cesium.Color.YELLOW
		 		_this.viewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
		 	}
		 	else if(pick.id==_this.id+"-Z"){
		 		_this._primitiveZ.appearance.material.uniforms.color=Cesium.Color.YELLOW
		 		_this.viewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
		 	}
		 	else if(pick.id==_this.id+"-XY"){
			    var attributes = _this._primitiveXY.getGeometryInstanceAttributes(pick.id);
			    if(attributes){
			    	attributes.color =Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.YELLOW)
			    }
		 		_this.viewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
		 	}
		 	else if(selectedAxis.id==_this.id+"-XZ"){
			    var attributes = _this._primitiveXZ.getGeometryInstanceAttributes(selectedAxis.id);
			    if(attributes){
			    	attributes.color =Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.YELLOW)
			    }
			    _this.viewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
		 	}
		 	else if(selectedAxis.id==_this.id+"-YZ"){
			    var attributes = _this._primitiveYZ.getGeometryInstanceAttributes(selectedAxis.id);
			    if(attributes){
			    	attributes.color =Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.YELLOW)
			    }
			    _this.viewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
		 	}
		}
	},Cesium.ScreenSpaceEventType.LEFT_DOWN);
    
	//鼠标左键释放
	this._handler.setInputAction(function(e) {
		if(selectedAxis){
		 	if(selectedAxis.id==_this.id+"-X"){
		 		_this._primitiveX.appearance.material.uniforms.color=Cesium.Color.RED;
		 	}
		 	else if(selectedAxis.id==_this.id+"-Y"){
		 		_this._primitiveY.appearance.material.uniforms.color=Cesium.Color.GREEN
		 	}
		 	else if(selectedAxis.id==_this.id+"-Z"){
		 		_this._primitiveZ.appearance.material.uniforms.color=Cesium.Color.BLUE
		 	}
		 	else if(selectedAxis.id==_this.id+"-XY"){
			    var attributes = _this._primitiveXY.getGeometryInstanceAttributes(selectedAxis.id);
			    if(attributes){
			    	attributes.color =Cesium.ColorGeometryInstanceAttribute.toValue(new Cesium.Color(1.0, 0.0, 0.0, 0.3))
			    }
		 	}
		 	else if(selectedAxis.id==_this.id+"-XZ"){
			    var attributes = _this._primitiveXZ.getGeometryInstanceAttributes(selectedAxis.id);
			    if(attributes){
			    	attributes.color =Cesium.ColorGeometryInstanceAttribute.toValue(new Cesium.Color(1.0, 0.0, 0.0, 0.3))
			    }
		 	}
		 	else if(selectedAxis.id==_this.id+"-YZ"){
			    var attributes = _this._primitiveYZ.getGeometryInstanceAttributes(selectedAxis.id);
			    if(attributes){
			    	attributes.color =Cesium.ColorGeometryInstanceAttribute.toValue(new Cesium.Color(1.0, 0.0, 0.0, 0.3)) 
			    }
		 	}
		 	selectedAxis=null;
	        this.pickPoint = null
		}
		_this.viewer.scene.screenSpaceCameraController.enableRotate = true;//解锁相机
	},Cesium.ScreenSpaceEventType.LEFT_UP);
	
	this._handler.setInputAction(function(movement) {
		if(selectedAxis){
		 	if(selectedAxis.id==_this.id+"-X"){
		 		_this._moveX(movement);
		 	}
		 	else if(selectedAxis.id==_this.id+"-Y"){
		 		_this._moveY(movement);
		 	}
		 	else if(selectedAxis.id==_this.id+"-Z"){
		 		_this._moveZ(movement);
		 	}
		 	else if(selectedAxis.id==_this.id+"-XY"){
		 		_this._precessTranslationPlane(movement,'XY');
		 	}
		 	else if(selectedAxis.id==_this.id+"-XZ"){
		 		_this._precessTranslationPlane(movement,'XZ');
		 	}
		 	else if(selectedAxis.id==_this.id+"-YZ"){
		 		_this._precessTranslationPlane(movement,'YZ');
		 	}
		}
	}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
	
	this._handler.setInputAction(function(movement) {
		_this.destroy();
	}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
	
};


VFG.OrbitControls.prototype.getModelMatrix=function () {
	return Cesium.Matrix4.multiplyByUniformScale(Cesium.Transforms.eastNorthUpToFixedFrame(this.position),this.scale*1.5, new Cesium.Matrix4())
}

VFG.OrbitControls.prototype.getModelMatrixXY=function(){
    var dimensions = new Cesium.Cartesian3(this.scale*0.1, this.scale*0.1, this.scale*0.1);
    var scaleMatrix = Cesium.Matrix4.fromScale(dimensions);
    var xPlaneMatrix=Cesium.Matrix4.multiply(Cesium.Transforms.eastNorthUpToFixedFrame(this.position), scaleMatrix, new Cesium.Matrix4());
	Cesium.Matrix4.multiplyByTranslation(
		xPlaneMatrix,
        Cesium.Cartesian3.multiplyByScalar(Cesium.Cartesian3.UNIT_X, 0.5, new Cesium.Cartesian3()),
        xPlaneMatrix
    );
	Cesium.Matrix4.multiplyByTranslation(
		xPlaneMatrix,
        Cesium.Cartesian3.multiplyByScalar(Cesium.Cartesian3.UNIT_Y, 0.5, new Cesium.Cartesian3()),
        xPlaneMatrix
    );
	return xPlaneMatrix;
}

VFG.OrbitControls.prototype.getModelMatrixXZ=function(){
    var xPlaneMatrix=this.getModelMatrixXY();
    
    var mx = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(90));
    var rotationX = Cesium.Matrix4.fromRotationTranslation(mx);
    Cesium.Matrix4.multiply(
    		xPlaneMatrix,
            rotationX,
            xPlaneMatrix
    );
    
    Cesium.Matrix4.multiplyByTranslation(
    		xPlaneMatrix,
            Cesium.Cartesian3.multiplyByScalar(Cesium.Cartesian3.UNIT_Z, 0.5, new Cesium.Cartesian3()),
            xPlaneMatrix
        );
    Cesium.Matrix4.multiplyByTranslation(
    		xPlaneMatrix,
            Cesium.Cartesian3.multiplyByScalar(Cesium.Cartesian3.UNIT_Y, 0.5, new Cesium.Cartesian3()),
            xPlaneMatrix
        );
	return xPlaneMatrix;
}

VFG.OrbitControls.prototype.getModelMatrixYZ=function(){
    var xPlaneMatrix=this.getModelMatrixXY();
    
    var mx = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(90));
    var rotationX = Cesium.Matrix4.fromRotationTranslation(mx);
    Cesium.Matrix4.multiply(
    		xPlaneMatrix,
            rotationX,
            xPlaneMatrix
    );
    Cesium.Matrix4.multiplyByTranslation(
    		xPlaneMatrix,
            Cesium.Cartesian3.multiplyByScalar(Cesium.Cartesian3.UNIT_X, -0.5, new Cesium.Cartesian3()),
            xPlaneMatrix
        );
    Cesium.Matrix4.multiplyByTranslation(
    		xPlaneMatrix,
            Cesium.Cartesian3.multiplyByScalar(Cesium.Cartesian3.UNIT_Z, -0.5, new Cesium.Cartesian3()),
            xPlaneMatrix
        );
	return xPlaneMatrix;
}



/**
 * 处理选中
 * @param e{startPosition: Cesium.Cartesian2, endPosition: Cesium.Cartesian2}}
 * @param axis{ArrowPolyline}
 * @private
 */
VFG.OrbitControls.prototype._precessTranslation=function (e, axis) {

    if (!this.pickPoint) return
    this.viewer.camera.getPickRay(e.startPosition, this.pickRay)
    const startPosition = this.getPlanePosition(this.pickPoint, this.viewer.camera.position.clone(), this.pickRay, axis.direction)
    this.viewer.camera.getPickRay(e.endPosition, this.pickRay)
    const endPosition = this.getPlanePosition(this.pickPoint, this.viewer.camera.position.clone(), this.pickRay, axis.direction)
    const moveVector = new Cesium.Cartesian3()
    Cesium.Cartesian3.subtract(endPosition, startPosition, moveVector)
    const moveLength = -Cesium.Cartesian3.dot(axis.direction, moveVector)
    this.translation(moveVector, axis.unit, moveLength)

}

VFG.OrbitControls.prototype._precessTranslationPlane=function (e, axis) {
	if (!this.pickPoint) return
	if('XY'==axis){
	   this._moveX(e);
	   this._moveY(e);
	 }
	else if('XZ'==axis){
	   this._moveX(e);
	   this._moveZ(e);
	}else{
	   this._moveY(e);
	   this._moveZ(e);
	}
}

VFG.OrbitControls.prototype._moveX=function (e) {
	if (!this.pickPoint) return
    this.viewer.camera.getPickRay(e.startPosition, this.pickRay)
    const startPosition = this.getPlanePosition(this.pickPoint, this.viewer.camera.position.clone(), this.pickRay, this.axisX.direction)
    this.viewer.camera.getPickRay(e.endPosition, this.pickRay)
    const endPosition = this.getPlanePosition(this.pickPoint, this.viewer.camera.position.clone(), this.pickRay, this.axisX.direction)
    const moveVector = new Cesium.Cartesian3()
    Cesium.Cartesian3.subtract(endPosition, startPosition, moveVector)
    const moveLength = -Cesium.Cartesian3.dot(this.axisX.direction, moveVector)
    this.translation(moveVector,  this.axisX.unit, moveLength)
}

VFG.OrbitControls.prototype._moveY=function (e) {
	if (!this.pickPoint) return
    this.viewer.camera.getPickRay(e.startPosition, this.pickRay)
    const startPosition = this.getPlanePosition(this.pickPoint, this.viewer.camera.position.clone(), this.pickRay, this.axisY.direction)
    this.viewer.camera.getPickRay(e.endPosition, this.pickRay)
    const endPosition = this.getPlanePosition(this.pickPoint, this.viewer.camera.position.clone(), this.pickRay, this.axisY.direction)
    const moveVector = new Cesium.Cartesian3()
    Cesium.Cartesian3.subtract(endPosition, startPosition, moveVector)
    const moveLength = -Cesium.Cartesian3.dot(this.axisY.direction, moveVector)
    this.translation(moveVector,  this.axisY.unit, moveLength)
}

VFG.OrbitControls.prototype._moveZ=function (e) {
	if (!this.pickPoint) return
    this.viewer.camera.getPickRay(e.startPosition, this.pickRay)
    const startPosition = this.getPlanePosition(this.pickPoint, this.viewer.camera.position.clone(), this.pickRay, this.axisZ.direction)
    this.viewer.camera.getPickRay(e.endPosition, this.pickRay)
    const endPosition = this.getPlanePosition(this.pickPoint, this.viewer.camera.position.clone(), this.pickRay, this.axisZ.direction)
    const moveVector = new Cesium.Cartesian3()
    Cesium.Cartesian3.subtract(endPosition, startPosition, moveVector)
    const moveLength = -Cesium.Cartesian3.dot(this.axisZ.direction, moveVector)
    this.translation(moveVector,  this.axisZ.unit, moveLength)
}

/**
 * 获取平面上的位置
 * @param position{Cesium.Cartesian3} 模型位置
 * @param cameraPosition{Cesium.Cartesian3} 相机位置
 * @param pickRay{Cesium.Ray} 从相机到屏幕的射线
 * @param axisDirection{Cesium.Cartesian3} 轴的向量
 */
VFG.OrbitControls.prototype.getPlanePosition =function(position, cameraPosition, pickRay, axisDirection) {
    // 第一步, 获取相机在轴上的投影
    const cartesian3 = Cesium.Cartesian3.subtract(cameraPosition, position, new Cesium.Cartesian3())
    const length = Cesium.Cartesian3.dot(cartesian3, axisDirection)
    // 获取轴上投影的位置, 以相机到这个位置, 为平面法线
    Cesium.Cartesian3.multiplyByScalar(axisDirection, length, cartesian3);
    Cesium.Cartesian3.add(position, cartesian3, cartesian3)
    const pn = Cesium.Cartesian3.subtract(cameraPosition, cartesian3, new Cesium.Cartesian3())
    // 获取单位向量, 射线向投影向量投影
    Cesium.Cartesian3.normalize(pn, cartesian3)
    const number = Cesium.Cartesian3.dot(pickRay.direction, cartesian3)
    // 获取射线与平面相交点
    const number1 = Cesium.Cartesian3.magnitude(pn)
    Cesium.Cartesian3.multiplyByScalar(pickRay.direction, number1/number, cartesian3);
    return cartesian3
}

VFG.OrbitControls.prototype.rayPlaneIntersection=function(ray,cameraDirection,pickPoint){
  if (!pickPoint) {
	  return
  }
  var result = new Cesium.Cartesian3()
  var number = Cesium.Cartesian3.dot(cameraDirection, pickPoint);
  var number1 = Cesium.Cartesian3.dot(cameraDirection, ray.origin);
  var number2 = Cesium.Cartesian3.dot(cameraDirection, ray.direction);
  var t = (number - number1) / number2;
  return Cesium.Cartesian3.add(ray.origin, Cesium.Cartesian3.multiplyByScalar(ray.direction, t, result), result);
}

/**
 * 平移
 * @param moveVector{Cesium.Cartesian3} 移动距离
 * @param unit
 * @param moveLength
 */
VFG.OrbitControls.prototype.translation=function(moveVector, axisUnit, moveLength){
	let factor=(1/(this.scale*2));
	Cesium.Matrix4.multiplyByTranslation(
        this._primitiveX.modelMatrix,
        Cesium.Cartesian3.multiplyByScalar(axisUnit, moveLength*factor, new Cesium.Cartesian3()),
        this._primitiveX.modelMatrix
    );
	Cesium.Matrix4.multiplyByTranslation(
        this._primitiveY.modelMatrix,
        Cesium.Cartesian3.multiplyByScalar(axisUnit, moveLength*factor, new Cesium.Cartesian3()),
        this._primitiveY.modelMatrix
    )
	Cesium.Matrix4.multiplyByTranslation(
        this._primitiveZ.modelMatrix,
        Cesium.Cartesian3.multiplyByScalar(axisUnit, moveLength*factor, new Cesium.Cartesian3()),
        this._primitiveZ.modelMatrix
    )	
    Cesium.Matrix4.getTranslation(Cesium.Matrix4.multiplyByUniformScale(this._primitiveZ.modelMatrix,1, new Cesium.Matrix4()), this.position);
	
	this._primitiveXY.modelMatrix=this.getModelMatrixXY();
	this._primitiveXZ.modelMatrix=this.getModelMatrixXZ();
	this._primitiveYZ.modelMatrix=this.getModelMatrixYZ();
	if(this.options.callback){
		this.options.callback(this.position);
	}
	
}
VFG.OrbitControls.prototype.getPostition=function (){
	var cartesian3=new Cesium.Cartesian3 ();
	Cesium.Matrix4.getTranslation(this._primitiveZ.modelMatrix,cartesian3);
	return cartesian3
}
VFG.OrbitControls.prototype.destroy = function () {
  if(this._primitiveX){
	  this.viewer.scene.primitives.remove( this._primitiveX );
  }
  if(this._primitiveY){
	  this.viewer.scene.primitives.remove( this._primitiveY );
  }
  if(this._primitiveZ){
	  this.viewer.scene.primitives.remove( this._primitiveZ );
  }
  if(this._primitiveXY){
	  this.viewer.scene.primitives.remove( this._primitiveXY );
  }
  if(this._primitiveXZ){
	  this.viewer.scene.primitives.remove( this._primitiveXZ );
  }
  if(this._primitiveYZ){
	  this.viewer.scene.primitives.remove( this._primitiveYZ );
  }
  if(this.options.end){
		this.options.end(this.position);
  }
  if( this._handler){
	  this._handler.destroy();
	  this._handler= null;
  };
  delete this.viewer;
  return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="EditRoadMark.js" />
VFG.EditRoadMark=function(viewer,entity){
	this.viewer=viewer;
	this.tip=new VFG.Tip(viewer);
	this.entity=entity;
	this.position=entity.position||null;
	this.model=entity;
	
	this.init();
}
VFG.EditRoadMark.prototype.init=function(){
	var _this=this;
	
	_this.rectMin=new Cesium.Cartesian3 (this.entity.thing.coordinates[0].x , this.entity.thing.coordinates[0].y ,this.entity.thing.coordinates[0].z );  
	_this.rectMax=new Cesium.Cartesian3 (this.entity.thing.coordinates[1].x , this.entity.thing.coordinates[1].y ,this.entity.thing.coordinates[1].z );  
	
	_this.rectMinPoint=_this.viewer.entities.add({
		id:_this.entity.id+'-rectMin',
        position: new Cesium.CallbackProperty(function (time) {
            return _this.rectMin;
        }, false),
        point:{
            color: Cesium.Color.VIOLET  ,
            pixelSize:10,
        }
    });
	
	_this.rectMaxPoint=_this.viewer.entities.add({
		id:_this.entity.id+'-rectMax',
        position: new Cesium.CallbackProperty(function (time) {
            return _this.rectMax;
        }, false),
        point:{
            color: Cesium.Color.VIOLET  ,
            pixelSize:10,
        }
    });
	
	var rectangle = Cesium.Rectangle.fromCartesianArray(_this.entity.thing.coordinates);
    var center = Cesium.Rectangle.center(rectangle);
    _this.rectCenter= Cesium.Cartographic.toCartesian(center);
    
	_this.rectCenterPoint=_this.viewer.entities.add({
		id:_this.entity.id+'-rectCenter',
        position: new Cesium.CallbackProperty(function (time) {
            return  _this.rectCenter;
        }, false),
        point:{
            color: Cesium.Color.VIOLET  ,
            pixelSize:10,
        }
    });
	
	this._handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
	
	//鼠标左键按下
	this._handler.setInputAction(function(e) {
		let pick = _this.viewer.scene.pick(e.position);
		if(Cesium.defined(pick) && Cesium.defined(pick.id)){
			if(pick.id.id==_this.entity.id+'-rectMax' ){
				_this.pickEntity=pick;
				_this.rectMaxPoint.point.color=Cesium.Color.YELLOW;
		 		_this.viewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
			}
			if(pick.id.id==_this.entity.id+'-rectMin' ){
				_this.pickEntity=pick;
				_this.rectMinPoint.point.color=Cesium.Color.YELLOW;
		 		_this.viewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
			}
			if(pick.id.id==_this.entity.id+'-rectCenter' ){
				_this.pickEntity=pick;
				_this.rectCenterPoint.point.color=Cesium.Color.YELLOW;
		 		_this.viewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
			}
		}
	},Cesium.ScreenSpaceEventType.LEFT_DOWN);
    
	this._handler.setInputAction(function(e) {
		if(_this.pickEntity){
			if(_this.pickEntity.id.id==_this.entity.id+'-rectMax' ){
				_this.rectMaxPoint.point.color=Cesium.Color.VIOLET;
			}
			if(_this.pickEntity.id.id==_this.entity.id+'-rectMin' ){
				_this.rectMinPoint.point.color=Cesium.Color.VIOLET;
			}
			if(_this.pickEntity.id.id==_this.entity.id+'-rectCenter' ){
				_this.rectCenterPoint.point.color=Cesium.Color.VIOLET;
			}
		}
		_this.viewer.scene.screenSpaceCameraController.enableRotate = true;
		_this.tip.setVisible(false);
		_this.pickEntity=null;
	},Cesium.ScreenSpaceEventType.LEFT_UP);
	
	this._handler.setInputAction(function(movement) {
		let pick = _this.viewer.scene.pick(movement.endPosition);
		if(Cesium.defined(pick) && Cesium.defined(pick.id) && _this.pickEntity==null){
			if(pick.id.id==_this.entity.id+'-rectCenter' ||pick.id.id==_this.entity.id+'-rectMax' || pick.id.id==_this.entity.id+'-rectMin'){
				_this.tip.setVisible(true);
				_this.tip.showAt(movement.endPosition,"按住鼠标左键可拖动位置。");
			}else{
				_this.tip.setVisible(false);
			}
		}else{
			_this.tip.setVisible(false);
		}
		
		if(_this.pickEntity && Cesium.defined(_this.pickEntity.id)){
			if(_this.pickEntity.id.id==_this.entity.id+'-rectCenter'){
				let startC3=VFG.Util.getScreenToC3(_this.viewer, movement.startPosition, _this.pickEntity);
				let endC3=VFG.Util.getScreenToC3(_this.viewer, movement.endPosition, _this.pickEntity);
				if(Cesium.defined(startC3) && Cesium.defined(endC3)){
					_this.move(startC3,endC3);
					_this.tip.setVisible(true);
					_this.tip.showAt(movement.endPosition,"调整中...");
				}
			}
			if(_this.pickEntity.id.id==_this.entity.id+'-rectMin'){
				let endC3=VFG.Util.getScreenToC3(_this.viewer, movement.endPosition, _this.pickEntity);
				if(Cesium.defined(endC3)){
					_this.moveMin(endC3);
					_this.tip.setVisible(true);
					_this.tip.showAt(movement.endPosition,"调整中...");
				}
			}
			if(_this.pickEntity.id.id==_this.entity.id+'-rectMax'){
				let endC3=VFG.Util.getScreenToC3(_this.viewer, movement.endPosition, _this.pickEntity);
				if(Cesium.defined(endC3)){
					_this.moveMax(endC3);
					_this.tip.setVisible(true);
					_this.tip.showAt(movement.endPosition,"调整中...");
				}
			}
		}
	}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
	
	this._handler.setInputAction(function(movement) {
	}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
}


VFG.EditRoadMark.prototype.on = function(type,callback) {
	if('change'==type){
		this.change=callback;
	}
};

VFG.EditRoadMark.prototype.move = function(oldPosition,newPosition) {
	let _this=this;
	let diff = Cesium.Cartesian3.subtract(newPosition, oldPosition, new Cesium.Cartesian3());
	_this.rectMin=Cesium.Cartesian3.add(_this.rectMin, diff, new Cesium.Cartesian3());
	_this.rectMax=Cesium.Cartesian3.add(_this.rectMax, diff, new Cesium.Cartesian3());
    _this.rectCenter= Cesium.Cartographic.toCartesian(Cesium.Rectangle.center(Cesium.Rectangle.fromCartesianArray([_this.rectMin,_this.rectMax])));
    if(this.entity){
    	this.entity.updateCoordinates([_this.rectMin,_this.rectMax],true);
    }
};

VFG.EditRoadMark.prototype.moveMin = function(minPosition) {
	let _this=this;
	_this.rectMin=minPosition;
    _this.rectCenter= Cesium.Cartographic.toCartesian(Cesium.Rectangle.center(Cesium.Rectangle.fromCartesianArray([_this.rectMin,_this.rectMax])));
    if(this.entity){
    	this.entity.updateCoordinates([_this.rectMin,_this.rectMax],true);
    }
};

VFG.EditRoadMark.prototype.moveMax = function(maxPosition) {
	let _this=this;
	_this.rectMax=maxPosition;
    _this.rectCenter= Cesium.Cartographic.toCartesian(Cesium.Rectangle.center(Cesium.Rectangle.fromCartesianArray([_this.rectMin,_this.rectMax])));
    if(this.entity){
    	this.entity.updateCoordinates([_this.rectMin,_this.rectMax],true);
    }
};

VFG.EditRoadMark.prototype.destroy = function() {
    if( this._handler){
    	this._handler.destroy();
    	this._handler = null;
    };
    if(this.tip){
    	this.tip.destroy();
    }
    if(this.rectMaxPoint){
    	this.viewer.entities.remove(this.rectMaxPoint);
    }
    if(this.rectMinPoint){
    	this.viewer.entities.remove(this.rectMinPoint);
    }
    if(this.rectCenterPoint){
    	this.viewer.entities.remove(this.rectCenterPoint);
    }
    delete this.rectMaxPoint;
    delete this.rectMinPoint;
    delete this.rectCenterPoint;
    delete this.tip;
    delete this._handler;
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="PPoint.js" />
VFG.PPoint=function(viewer, options,collection) {
	this.viewer = viewer;
	this.options = options;
	this.collection=collection;
	this.parentId= options.parentId||'';
	this.id= options.id;
	this.name= options.name||'';
	this.code= options.code||'';
	this.type= options.type||'';
	this.position=options.position||null;
	this.orientation=options.orientation||{};
	
	this.thing=options.thing||{};
	
	this.attribute=options.attribute||{};
	this.propertys=options.propertys||[];
	this.init();
}

VFG.PPoint.prototype.init = function() {
	
	if(this.thing.bShow=='1'){
		this.bPrimitive=this.viewer.scene.primitives.get(2).add(this.getBillboard());
	}
	
	if(this.thing.lShow=='1'){
		this.lPrimitive=this.viewer.scene.primitives.get(1).add(this.getLabel());
	}
	
	if(this.thing.pShow=='1'){
		this.pPrimitive=this.viewer.scene.primitives.get(0).add(this.getPoint());
	}
	
};


VFG.PPoint.prototype.getBillboard=function(){
	let param={
		id:this.id,
		image :this.thing.image,
		scale:this.thing.scale||1 ,
	}
	if(this.thing.height){
		param.height=this.thing.height *1
	}
	
	if(this.thing.width){
		param.width=this.thing.width *1
	}
	param.position = this.getPosition();
	param.verticalOrigin=Cesium.VerticalOrigin.BOTTOM;
	
	if(this.thing.isBScaleByDistance=='1' ){
		param.scaleByDistance=new Cesium.NearFarScalar(
			this.thing.bScaleByDistanceNear? this.thing.bScaleByDistanceNear*1: this.position.z*1,
			this.thing.bScaleByDistanceNearValue? this.thing.bScaleByDistanceNearValue*1: 1,
			this.thing.bScaleByDistanceFar? this.thing.bScaleByDistanceFar*1: 10000,
			this.thing.bScaleByDistanceFarValue? this.thing.bScaleByDistanceFarValue*1: 0);
	}
	
	if(this.thing.isBTranslucencyByDistance=='1' ){
		param.translucencyByDistance=new Cesium.NearFarScalar(
			this.thing.bTranslucencyByDistanceNear? this.thing.bTranslucencyByDistanceNear*1: this.position.z*1,
			this.thing.bTranslucencyByDistanceNearValue? this.thing.bTranslucencyByDistanceNearValue*1: 1,
			this.thing.bTranslucencyByDistanceFar? this.thing.bTranslucencyByDistanceFar*1: 10000,
			this.thing.bTranslucencyByDistanceFarValue? this.thing.bTranslucencyByDistanceFarValue*1: 0);
	}
	return param;
	
}

VFG.PPoint.prototype.updateBScaleByDistance=function(param){
	
	if(param.near){
		this.thing.bScaleByDistanceNear=param.near
	}
	if(param.nearValue){
		this.thing.bScaleByDistanceNearValue=param.nearValue
	}
	if(param.far){
		this.thing.bScaleByDistanceFar=param.far
	}
	if(param.farValue){
		this.thing.bScaleByDistanceFarValue=param.farValue
	}
	if(param.isBScaleByDistance){
		this.thing.isBScaleByDistance=param.isScaleByDistance
	}
	if(!this.bPrimitive){
		return;
	}
	if(this.thing.isBScaleByDistance=='1' ){
		this.bPrimitive.scaleByDistance=new Cesium.NearFarScalar(
			this.thing.bScaleByDistanceNear? this.thing.bScaleByDistanceNear*1: this.position.z*1,
			this.thing.bScaleByDistanceNearValue? this.thing.bScaleByDistanceNearValue*1: 1,
			this.thing.bScaleByDistanceFar? this.thing.bScaleByDistanceFar*1: 10000,
			this.thing.bScaleByDistanceFarValue? this.thing.bScaleByDistanceFarValue*1: 0);
	}else{
		this.bPrimitive.scaleByDistance=undefined;
	}
}

VFG.PPoint.prototype.updateBTranslucencyByDistance=function(param){
	
	if(param.near){
		this.thing.bTranslucencyByDistanceNear=param.near
	}
	if(param.nearValue){
		this.thing.bTranslucencyByDistanceNearValue=param.nearValue
	}
	if(param.far){
		this.thing.bTranslucencyByDistanceFar=param.far
	}
	if(param.farValue){
		this.thing.bTranslucencyByDistanceFarValue=param.farValue
	}
	if(param.isTranslucencyByDistance){
		this.thing.isBTranslucencyByDistance=param.isTranslucencyByDistance
	}
	
	if(!this.bPrimitive){
		return;
	}
	
	if(this.thing.isBTranslucencyByDistance=='1' ){
		this.bPrimitive.translucencyByDistance=new Cesium.NearFarScalar(
			this.thing.bTranslucencyByDistanceNear? this.thing.bTranslucencyByDistanceNear*1: this.position.z*1,
			this.thing.bTranslucencyByDistanceNearValue? this.thing.bTranslucencyByDistanceNearValue*1: 1,
			this.thing.bTranslucencyByDistanceFar? this.thing.bTranslucencyByDistanceFar*1: 10000,
			this.thing.bTranslucencyByDistanceFarValue? this.thing.bTranslucencyByDistanceFarValue*1: 0);
	}else{
		this.bPrimitive.translucencyByDistance=undefined;
	}
}


VFG.PPoint.prototype.getLabel=function(){
	
	let param={
		id:this.id,
		text :this.name,
		font :(this.thing.lFontSize?this.thing.lFontSize:'13px') +" "+(this.thing.lFontFamily?this.thing.lFontFamily:'sans-serif'),
		scale :this.thing.lScale ? this.thing.lScale*1:1,
	}

	if(this.thing.lShowBackground && '1'==this.thing.lShowBackground){
		param.showBackground=true
	}
	
	if(this.thing.lBackgroundColor ){
		param.backgroundColor=this.thing.lBackgroundColor ? Cesium.Color.fromCssColorString(this.thing.lBackgroundColor):Cesium.Color.YELLOW 
	}
	
	if(this.thing.lOutlineWidth){
		param.outlineWidth=this.thing.lOutlineWidth *1
	}
	if(this.thing.lOutlineColor ){
		param.outlineColor=this.thing.lOutlineColor ? Cesium.Color.fromCssColorString(this.thing.lOutlineColor):Cesium.Color.YELLOW 
	}
	
	param.pixelOffset=new Cesium.Cartesian2(this.thing.lPOffsetX*1||0,this.thing.lPOffsetY*1||0);

	
	if(this.thing.lStyle ){
		if('FILL'==this.thing.lStyle ){
			param.style=Cesium.LabelStyle.FILL
		}
		if('FILL_AND_OUTLINE'==this.thing.lStyle  ){
			param.style=Cesium.LabelStyle.FILL_AND_OUTLINE
		}
		if('OUTLINE'==this.thing.lStyle){
			param.style=Cesium.LabelStyle.OUTLINE
		}
	}
	
	if(this.thing.lHorizontalOrigin){
		if('CENTER'==this.thing.lHorizontalOrigin){
			param.horizontalOrigin=Cesium.HorizontalOrigin.CENTER
		}
		
		if('LEFT'==this.thing.lHorizontalOrigin){
			param.horizontalOrigin=Cesium.HorizontalOrigin.LEFT 
		}
		
		if('RIGHT'==this.thing.lHorizontalOrigin){
			param.horizontalOrigin=Cesium.HorizontalOrigin.RIGHT
		}
	}
	
	if(this.thing.lVerticalOrigin ){
		if('BASELINE'==this.thing.lVerticalOrigin ){
			param.verticalOrigin=Cesium.VerticalOrigin.BASELINE 
		}
		if('BOTTOM'==this.thing.lVerticalOrigin ){
			param.verticalOrigin=Cesium.VerticalOrigin.BOTTOM 
		}
		if('CENTER'==this.thing.lVerticalOrigin ){
			param.verticalOrigin=Cesium.VerticalOrigin.CENTER  
		}
		if('TOP'==this.thing.lVerticalOrigin ){
			param.verticalOrigin=Cesium.VerticalOrigin.TOP  
		}
	}	
	param.position = this.getPosition();
	
	if(this.thing.isLScaleByDistance=='1' ){
		param.scaleByDistance=new Cesium.NearFarScalar(
			this.thing.lScaleByDistanceNear? this.thing.lScaleByDistanceNear*1: this.position.z*1,
			this.thing.lScaleByDistanceNearValue? this.thing.lScaleByDistanceNearValue*1: 1,
			this.thing.lScaleByDistanceFar? this.thing.lScaleByDistanceFar*1: 10000,
			this.thing.lScaleByDistanceFarValue? this.thing.lScaleByDistanceFarValue*1: 0);
	}
	
	if(this.thing.isLTranslucencyByDistance=='1' ){
		param.translucencyByDistance=new Cesium.NearFarScalar(
			this.thing.lTranslucencyByDistanceNear? this.thing.lTranslucencyByDistanceNear*1: this.position.z*1,
			this.thing.lTranslucencyByDistanceNearValue? this.thing.lTranslucencyByDistanceNearValue*1: 1,
			this.thing.lTranslucencyByDistanceFar? this.thing.lTranslucencyByDistanceFar*1: 10000,
			this.thing.lTranslucencyByDistanceFarValue? this.thing.lTranslucencyByDistanceFarValue*1: 0);
	}
	
	if(this.thing.isLPixelOffsetScaleByDistance=='1' ){
		param.pixelOffsetScaleByDistance=new Cesium.NearFarScalar(
			this.thing.lPixelOffsetScaleByDistanceNear? this.thing.lPixelOffsetScaleByDistanceNear*1: this.position.z*1,
			this.thing.lPixelOffsetScaleByDistanceNearValue? this.thing.lPixelOffsetScaleByDistanceNearValue*1: 1,
			this.thing.lPixelOffsetScaleByDistanceFar? this.thing.lPixelOffsetScaleByDistanceFar*1: 10000,
			this.thing.lPixelOffsetScaleByDistanceFarValue? this.thing.lPixelOffsetScaleByDistanceFarValue*1: 0);
	}
	return param;
}

VFG.PPoint.prototype.updateLScaleByDistance=function(param){
	
	if(param.near){
		this.thing.lScaleByDistanceNear=param.near
	}
	if(param.nearValue){
		this.thing.lScaleByDistanceNearValue=param.nearValue
	}
	if(param.far){
		this.thing.lScaleByDistanceFar=param.far
	}
	if(param.farValue){
		this.thing.lScaleByDistanceFarValue=param.farValue
	}
	if(param.isScaleByDistance){
		this.thing.isLScaleByDistance=param.isScaleByDistance
	}
	if(!this.lPrimitive){
		return;
	}
	
	if(this.thing.isLScaleByDistance=='1' ){
		this.lPrimitive.scaleByDistance=new Cesium.NearFarScalar(
			this.thing.lScaleByDistanceNear? this.thing.lScaleByDistanceNear*1: this.position.z*1,
			this.thing.lScaleByDistanceNearValue? this.thing.lScaleByDistanceNearValue*1: 1,
			this.thing.lScaleByDistanceFar? this.thing.lScaleByDistanceFar*1: 10000,
			this.thing.lScaleByDistanceFarValue? this.thing.lScaleByDistanceFarValue*1: 0);
	}else{
		this.lPrimitive.scaleByDistance=undefined;
	}
}

VFG.PPoint.prototype.updateLTranslucencyByDistance=function(param){
	if(param.near){
		this.thing.lTranslucencyByDistanceNear=param.near
	}
	if(param.nearValue){
		this.thing.lTranslucencyByDistanceNearValue=param.nearValue
	}
	if(param.far){
		this.thing.lTranslucencyByDistanceFar=param.far
	}
	if(param.farValue){
		this.thing.lTranslucencyByDistanceFarValue=param.farValue
	}
	if(param.isTranslucencyByDistance){
		this.thing.isLTranslucencyByDistance=param.isTranslucencyByDistance
	}
	
	if(!this.lPrimitive){
		return;
	}
	
	if(this.thing.isLTranslucencyByDistance=='1' ){
		this.lPrimitive.translucencyByDistance=new Cesium.NearFarScalar(
			this.thing.lTranslucencyByDistanceNear? this.thing.lTranslucencyByDistanceNear*1: this.position.z*1,
			this.thing.lTranslucencyByDistanceNearValue? this.thing.lTranslucencyByDistanceNearValue*1: 1,
			this.thing.lTranslucencyByDistanceFar? this.thing.lTranslucencyByDistanceFar*1: 10000,
			this.thing.lTranslucencyByDistanceFarValue? this.thing.lTranslucencyByDistanceFarValue*1: 0);
	}else{
		this.lPrimitive.translucencyByDistance=undefined;
	}
}

VFG.PPoint.prototype.updateLPixelOffsetScaleByDistance=function(param){
	
	if(param.near){
		this.thing.lPixelOffsetScaleByDistanceNear=param.near
	}
	if(param.nearValue){
		this.thing.lPixelOffsetScaleByDistanceNearValue=param.nearValue
	}
	if(param.far){
		this.thing.lPixelOffsetScaleByDistanceFar=param.far
	}
	if(param.farValue){
		this.thing.lPixelOffsetScaleByDistanceFarValue=param.farValue
	}
	if(param.isPixelOffsetScaleByDistance){
		this.thing.isLPixelOffsetScaleByDistance=param.isPixelOffsetScaleByDistance
	}
	
	if(!this.lPrimitive){
		return;
	}
	
	if(this.thing.isLPixelOffsetScaleByDistance=='1' ){
		this.lPrimitive.pixelOffsetScaleByDistance=new Cesium.NearFarScalar(
			this.thing.lPixelOffsetScaleByDistanceNear? this.thing.lPixelOffsetScaleByDistanceNear*1: this.position.z*1,
			this.thing.lPixelOffsetScaleByDistanceNearValue? this.thing.lPixelOffsetScaleByDistanceNearValue*1: 1,
			this.thing.lPixelOffsetScaleByDistanceFar? this.thing.lPixelOffsetScaleByDistanceFar*1: 10000,
			this.thing.lPixelOffsetScaleByDistanceFarValue? this.thing.lPixelOffsetScaleByDistanceFarValue*1: 0);
	}else{
		this.lPrimitive.pixelOffsetScaleByDistance=undefined;
	}
}


/**
 * 点
 */
VFG.PPoint.prototype.getPoint=function(){
	let param={
		id:this.id,
		pixelSize :this.thing.pSize*1||5,
		color :this.thing.pColor ? Cesium.Color.fromCssColorString(this.thing.pColor):Cesium.Color.RED,
	}
	if(this.thing.pOutlineColor){
		param.outlineColor=this.thing.pOutlineColor ? Cesium.Color.fromCssColorString(this.thing.pOutlineColor):Cesium.Color.YELLOW 
	}
	if(this.thing.pOutlineWidth){
		param.outlineWidth=this.thing.pOutlineWidth *1
	}
	param.position = this.getPosition();

	if(this.thing.isPScaleByDistance=='1' ){
		param.scaleByDistance=new Cesium.NearFarScalar(
			this.thing.pScaleByDistanceNear? this.thing.pScaleByDistanceNear*1: this.position.z*1,
			this.thing.pScaleByDistanceNearValue? this.thing.pScaleByDistanceNearValue*1: 1,
			this.thing.pScaleByDistanceFar? this.thing.pScaleByDistanceFar*1: 10000,
			this.thing.pScaleByDistanceFarValue? this.thing.pScaleByDistanceFarValue*1: 0);
	}
	
	if(this.thing.isPTranslucencyByDistance=='1' ){
		param.translucencyByDistance=new Cesium.NearFarScalar(
			this.thing.pTranslucencyByDistanceNear? this.thing.pTranslucencyByDistanceNear*1: this.position.z*1,
			this.thing.pTranslucencyByDistanceNearValue? this.thing.pTranslucencyByDistanceNearValue*1: 1,
			this.thing.pTranslucencyByDistanceFar? this.thing.pTranslucencyByDistanceFar*1: 10000,
			this.thing.pTranslucencyByDistanceFarValue? this.thing.pTranslucencyByDistanceFarValue*1: 0);
	}
	
	return param;
}


VFG.PPoint.prototype.updatePScaleByDistance=function(param){
	
	if(param.near){
		this.thing.pScaleByDistanceNear=param.near
	}
	if(param.nearValue){
		this.thing.pScaleByDistanceNearValue=param.nearValue
	}
	if(param.far){
		this.thing.pScaleByDistanceFar=param.far
	}
	if(param.farValue){
		this.thing.pScaleByDistanceFarValue=param.farValue
	}
	if(param.isScaleByDistance){
		this.thing.isPScaleByDistance=param.isScaleByDistance
	}
	
	if(!this.pPrimitive){
		return;
	}
	
	if(this.thing.isPScaleByDistance=='1' ){
		this.pPrimitive.scaleByDistance=new Cesium.NearFarScalar(
			this.thing.pScaleByDistanceNear? this.thing.pScaleByDistanceNear*1: this.position.z*1,
			this.thing.pScaleByDistanceNearValue? this.thing.pScaleByDistanceNearValue*1: 1,
			this.thing.pScaleByDistanceFar? this.thing.pScaleByDistanceFar*1: 10000,
			this.thing.pScaleByDistanceFarValue? this.thing.pScaleByDistanceFarValue*1: 0);
	}else{
		this.pPrimitive.scaleByDistance=undefined;
	}
}

VFG.PPoint.prototype.updatePTranslucencyByDistance=function(param){
	if(param.near){
		this.thing.pTranslucencyByDistanceNear=param.near
	}
	if(param.nearValue){
		this.thing.pTranslucencyByDistanceNearValue=param.nearValue
	}
	if(param.far){
		this.thing.pTranslucencyByDistanceFar=param.far
	}
	if(param.farValue){
		this.thing.pTranslucencyByDistanceFarValue=param.farValue
	}
	if(param.isTranslucencyByDistance){
		this.thing.isPTranslucencyByDistance=param.isTranslucencyByDistance
	}
	
	if(!this.pPrimitive){
		return;
	}
	
	if(this.thing.isPTranslucencyByDistance=='1' ){
		this.pPrimitive.translucencyByDistance=new Cesium.NearFarScalar(
			this.thing.pTranslucencyByDistanceNear? this.thing.pTranslucencyByDistanceNear*1: this.position.z*1,
			this.thing.pTranslucencyByDistanceNearValue? this.thing.pTranslucencyByDistanceNearValue*1: 1,
			this.thing.pTranslucencyByDistanceFar? this.thing.pTranslucencyByDistanceFar*1: 10000,
			this.thing.pTranslucencyByDistanceFarValue? this.thing.pTranslucencyByDistanceFarValue*1: 0);
	}else{
		this.pPrimitive.translucencyByDistance=undefined;
	}
}

VFG.PPoint.prototype.getPosition=function(){
	return Cesium.Cartesian3.fromDegrees(this.position.x*1,this.position.y*1,this.position.z*1);
}

VFG.PPoint.prototype.update=function(param){
	if(param.position){
		this.position=param.position;
		this.updatePosition(this.position);
	}
}

VFG.PPoint.prototype.updateName=function(param){
	this.name = param.name;
	this.code = param.code;
}

VFG.PPoint.prototype.updatePosition= function(position) {
	var _this = this;
	if(_this.position){
		this.position=position;
		if(this.bPrimitive){
			this.bPrimitive.position=this.getPosition();
		}
		if(this.pPrimitive){
			this.pPrimitive.position=this.getPosition();
		}
		if(this.lPrimitive){
			this.lPrimitive.position=this.getPosition();
		}
	}
};

VFG.PPoint.prototype.updateBShow=function(bShow){
	this.thing.bShow = bShow;
	if(this.bPrimitive){
		if("1"==this.thing.bShow){
			this.bPrimitive.show=true;
		}else{
			this.bPrimitive.show=false;
		}
	}else{
		this.bPrimitive=this.viewer.scene.primitives.get(2).add(this.getBillboard());
	}
}

VFG.PPoint.prototype.updateImage=function(param){
	this.thing.image = param.image;
	this.thing.height = param.height;
	this.thing.width = param.width;
	if(this.bPrimitive){
		this.bPrimitive.image=param.image;
		this.bPrimitive.height=param.height;
		this.bPrimitive.width=param.width;
	}
}

VFG.PPoint.prototype.updateBScale=function(scale){
	this.thing.scale = scale;
	if(this.bPrimitive){
		this.bPrimitive.scale=this.thing.scale;
	}
}


VFG.PPoint.prototype.updateLShow=function(show){
	this.thing.lShow = show;
	if(this.lPrimitive){
		if("1"==this.thing.lShow){
			this.lPrimitive.show=true;
		}else{
			this.lPrimitive.show=false;
		}
	}else{
		this.lPrimitive=this.viewer.scene.primitives.get(1).add(this.getLabel());
	}
}

VFG.PPoint.prototype.updateLBackgroundColor=function(backgroundColor){
	this.thing.lBackgroundColor = backgroundColor;
	if(this.lPrimitive){
		this.lPrimitive.backgroundColor=this.thing.lBackgroundColor ? Cesium.Color.fromCssColorString(this.thing.lBackgroundColor):Cesium.Color.YELLOW 
	}
}

VFG.PPoint.prototype.updateLShowBackground=function(showBackground){
	this.thing.lShowBackground = showBackground;
	if(this.lPrimitive){
		if('1'==this.thing.lShowBackground){
			this.lPrimitive.showBackground=true
		}else{
			this.lPrimitive.showBackground=false
		}
	}
}

VFG.PPoint.prototype.updateLStyle=function(style){
	this.thing.lStyle = style;
	if(this.lPrimitive){
		if('FILL'==this.thing.lStyle ){
			this.lPrimitive.style=Cesium.LabelStyle.FILL
		}
		if('FILL_AND_OUTLINE'==this.thing.lStyle  ){
			this.lPrimitive.style=Cesium.LabelStyle.FILL_AND_OUTLINE
		}
		if('OUTLINE'==this.thing.lStyle){
			this.lPrimitive.style=Cesium.LabelStyle.OUTLINE
		}
	}
}

VFG.PPoint.prototype.updateLOutlineWidth=function(lOutlineWidth){
	this.thing.lOutlineWidth = lOutlineWidth;
	if(this.lPrimitive){
		this.lPrimitive.outlineWidth=this.thing.lOutlineWidth *1
	}
}


VFG.PPoint.prototype.updateLOutlineColor=function(lOutlineColor){
	this.thing.lOutlineColor = lOutlineColor;
	if(this.lPrimitive){
		this.lPrimitive.outlineColor=this.thing.lOutlineColor ? Cesium.Color.fromCssColorString(this.thing.lOutlineColor):Cesium.Color.YELLOW 
	}
}

VFG.PPoint.prototype.updateLHorizontalOrigin=function(lHorizontalOrigin){
	this.thing.lHorizontalOrigin = lHorizontalOrigin;
	if(this.lPrimitive){
		if('CENTER'==this.thing.lHorizontalOrigin){
			this.lPrimitive.horizontalOrigin=Cesium.HorizontalOrigin.CENTER
		}
		
		if('LEFT'==this.thing.lHorizontalOrigin){
			this.lPrimitive.horizontalOrigin=Cesium.HorizontalOrigin.LEFT 
		}
		
		if('RIGHT'==this.thing.lHorizontalOrigin){
			this.lPrimitive.horizontalOrigin=Cesium.HorizontalOrigin.RIGHT
		}
	}
}

VFG.PPoint.prototype.updateLVerticalOrigin=function(lVerticalOrigin){
	this.thing.lVerticalOrigin = lVerticalOrigin;
	if(this.lPrimitive){
		if('BASELINE'==this.thing.lVerticalOrigin ){
			this.lPrimitive.verticalOrigin=Cesium.VerticalOrigin.BASELINE 
		}
		if('BOTTOM'==this.thing.lVerticalOrigin ){
			this.lPrimitive.verticalOrigin=Cesium.VerticalOrigin.BOTTOM 
		}
		if('CENTER'==this.thing.lVerticalOrigin ){
			this.lPrimitive.verticalOrigin=Cesium.VerticalOrigin.CENTER  
		}
		if('TOP'==this.thing.lVerticalOrigin ){
			this.lPrimitive.verticalOrigin=Cesium.VerticalOrigin.TOP  
		}
	}
}

VFG.PPoint.prototype.updateLScale=function(lScale){
	this.thing.lScale = lScale;
	if(this.lPrimitive){
		this.lPrimitive.scale=this.thing.lScale*1
	}
}

VFG.PPoint.prototype.updateLFontSize=function(fontSize){
	this.thing.lFontSize = fontSize;
	if(this.lPrimitive){
		try{
			this.lPrimitive.font=(this.thing.lFontSize?this.thing.lFontSize:'13px') +" "+(this.thing.lFontFamily?this.thing.lFontFamily:'sans-serif')
		}catch (e) {
		}
	}
}

VFG.PPoint.prototype.updateLFontFamily=function(lFontFamily){
	this.thing.lFontFamily = lFontFamily;
	if(this.lPrimitive){
		try{
			this.lPrimitive.font=(this.thing.lFontSize?this.thing.lFontSize:'13px') +" "+(this.thing.lFontFamily?this.thing.lFontFamily:'sans-serif')
		}catch (e) {
		}
	}
}

VFG.PPoint.prototype.updateLPOffset=function(lPOffsetX,lPOffsetY){
	this.thing.lPOffsetX = lPOffsetX;
	this.thing.lPOffsetY = lPOffsetY;
	if(this.lPrimitive){
		this.lPrimitive.pixelOffset=new Cesium.Cartesian2(this.thing.lPOffsetX*1,this.thing.lPOffsetY*1);
		this.lPrimitive.pixelOffsetScaleByDistance=new Cesium.NearFarScalar(this.position.z*1, 1,5000, 0.0);
	}
}

////////////////////////////////////////////
VFG.PPoint.prototype.updatePShow=function(show){
	this.thing.pShow = show;
	if(this.pPrimitive){
		if("1"==this.thing.pShow){
			this.pPrimitive.show=true;
		}else{
			this.pPrimitive.show=false;
		}
	}else{
		this.pPrimitive=this.viewer.scene.primitives.get(0).add(this.getPoint());
	}
}

VFG.PPoint.prototype.updatePOutlineColor=function(pOutlineColor){
	this.thing.pOutlineColor = pOutlineColor;
	if(this.pPrimitive){
		this.pPrimitive.outlineColor=this.thing.pOutlineColor ? Cesium.Color.fromCssColorString(this.thing.pOutlineColor):Cesium.Color.YELLOW 
	}
}

VFG.PPoint.prototype.updatePOutlineWidth=function(pOutlineWidth){
	this.thing.pOutlineWidth = pOutlineWidth;
	if(this.pPrimitive){
		this.pPrimitive.outlineWidth=this.thing.pOutlineWidth *1
	}
}

VFG.PPoint.prototype.updatePColor=function(pColor){
	this.thing.pColor = pColor;
	if(this.pPrimitive){
		this.pPrimitive.color =this.thing.pColor ? Cesium.Color.fromCssColorString(this.thing.pColor):Cesium.Color.RED;
	}
}

VFG.PPoint.prototype.updatePSize=function(pSize){
	this.thing.pSize = pSize;
	if(this.pPrimitive){
		this.pPrimitive.pixelSize =this.thing.pSize*1||5;
	}
}


VFG.PPoint.prototype.updateProperty= function(property) {
	var _this = this;
	if(_this.propertys){
		for(let index in _this.propertys){
			if(property.id==_this.propertys[index].id){
				_this.propertys.splice(index,1,property);
				return;
			}
		}
		_this.propertys.push(property);
	}
};

VFG.PPoint.prototype.removeProperty= function(id) {
	var _this = this;
	if(_this.propertys){
		for(let index in _this.propertys){
			if(id==_this.propertys[index].id){
				_this.propertys.splice(index,1);
				return;
			}
		}
	}
};

VFG.PPoint.prototype.destroy = function() {
	let _this=this;
	if(_this.bPrimitive){
		this.viewer.scene.primitives.get(2).remove(_this.bPrimitive);
	}
	if(_this.lPrimitive){
		this.viewer.scene.primitives.get(1).remove(_this.lPrimitive);
	}
	if(_this.pPrimitive){
		this.viewer.scene.primitives.get(0).remove(_this.pPrimitive);
	}
	
	delete this.position
	delete this.primity
	delete this.options
	delete this.model
    delete this.viewer
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="DrawPPoint.js" />
VFG.DrawPPoint=function(viewer,option){
	this.viewer=viewer;
	this.option=option;
	this.tip=new VFG.Tip(viewer);
	this.init();
}

VFG.DrawPPoint.prototype.init = function() {
	var _this=this;
	this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
	this.handler.setInputAction(function (movement) {
		let position=VFG.Util.getScreenToLnLa(_this.viewer, movement.position, null);
    	if (Cesium.defined(position)){
    		let entity=_this.render(position);
    		if(entity && _this.success){
    			_this.success(entity);
    		}
    	}
    },Cesium.ScreenSpaceEventType.LEFT_CLICK)
    
    this.handler.setInputAction(function (movement) {
    	_this.tip.showAt(movement.endPosition,"单击添加标注，右键取消！");
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
	this.handler.setInputAction(function (movement) {
		_this.destroy();
	}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
};

VFG.DrawPPoint.prototype.render = function(position) {
	var _this=this;
	if (Cesium.defined(position)){
		this.option.id=VFG.Util.getUuid();
		this.option.position=position;
		return new VFG.PPoint(_this.viewer,this.option);
	}
};

VFG.DrawPPoint.prototype.on=function(type,callback){
	if('success'==type){
		this.success=callback;
	}
	if('error'==type){
		this.error=callback;
	}
}


VFG.DrawPPoint.prototype.destroy = function() {
	if(this.complete){
		this.complete();
	}
    if( this.handler){
    	this.handler.destroy();
    	this.handler = null;
    };
    if(this.tip){
    	this.tip.destroy();
    }
	delete this.option;
    delete this.viewer;
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="EditPPoint.js" />
VFG.EditPPoint=function(viewer,entity){
	this.viewer=viewer;
	this.tip=new VFG.Tip(viewer);
	this.entity=entity;
	this.position=entity.position||null;
	this.cartesian3;
	this.init();
}
VFG.EditPPoint.prototype.init=function(){
	var _this=this;
	this.cartesian3 = Cesium.Cartesian3.fromDegrees(this.position.x*1, this.position.y*1,this.position.z*1+1);
	this.orbitControls=new VFG.OrbitControls(this.viewer,{
		id:this.entity.id,
		position:this.cartesian3,
		scale:15,
		callback:function(position){
			_this.cartesian3=position;
			let LnLa = VFG.Util.getLnLaFormC3(_this.viewer, position);
			if (Cesium.defined(LnLa)) {
				let new_position={
					x:LnLa.x,
					y:LnLa.y,
					z:LnLa.z*1-1,
				};
				if(_this.change){
					_this.change({
						position:new_position
					});
				}
				if(_this.entity){
					_this.entity.update({
						position:new_position
					});
				}
			}
		}
	})
}


VFG.EditPPoint.prototype.on = function(type,callback) {
	if('change'==type){
		this.change=callback;
	}
};

VFG.EditPPoint.prototype.destroy = function() {
    if(this.orbitControls){
    	this.orbitControls.destroy();
    }
    if( this._handler){
    	this._handler.destroy();
    	this._handler = null;
    };
    if(this.tip){
    	this.tip.destroy();
    }
	delete this.orbitControls;
    delete this.viewer;
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="Listener.js" />
VFG.Listener=function(viewer,option){
	this.option = Cesium.defaultValue(option, Cesium.defaultValue.EMPTY_OBJECT);
	if (!option) {
		console.log('参数必填!');
		return;
	}
	if (!viewer) {
		console.log('参数必填!');
		return;
	}
	
	this.position = option.position;
	if(!this.position){
		console.log('参数必填!');
		return;
	}
	this.option = option;
	this.viewer = viewer;
	this.position = Cesium.Cartesian3.fromDegrees(option.position.x*1, option.position.y*1, option.position.z*1);
	this.callback = option.callback;
	this.init();
}

/**
 * 初始化
 */
VFG.Listener.prototype.init=function(){
	var _this=this;
	if(_this.position){
		_this.event=function(){
			var cartesian2=Cesium.SceneTransforms.wgs84ToWindowCoordinates(_this.viewer.scene, _this.position);
			if (Cesium.defined(cartesian2)){
				if(_this.callback){
					_this.callback(cartesian2);
				}
			}
		}
		_this.viewer.scene.postRender.addEventListener(_this.event);
	}else{
		console.log('初始化失败，检测是否有效经纬度!!!');
	}
}

/**
 * 销毁
 */
VFG.Listener.prototype.destroy=function(){
	var _this = this;
	if(_this.event){
		_this.viewer.scene.postRender.removeEventListener(_this.event);
	}
	_this.event=null;
	delete this.option,
	delete this.callback,
	delete this.viewer,
	delete this.position;
	delete this.event;
	return Cesium.destroyObject(this);
}
;
///<jscompress sourcefile="DrawCircle.js" />
VFG.DrawCircle=function(viewer,option){
	this.viewer=viewer;
	this.option=option;
	this.id=option.id;
	this.thing=option.thing;
	this.position=null;
	this.tip=new VFG.Tip(viewer);
	this.enity;
	this.positions=[];
	this.init();
	this.LEFT_CLICK_TIMES=0;
}

VFG.DrawCircle.prototype.init=function() {
	let _this=this;
	this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
	this.handler.setInputAction(function (movement) {
		let cartesian3=VFG.Util.getScreenToC3 (_this.viewer, movement.position, _this.enity) 
		if(Cesium.defined(cartesian3)){
			if (_this.positions.length == 0) {
	        	_this.positions.push(cartesian3.clone());
	        }
			_this.positions.push(cartesian3);
			_this.LEFT_CLICK_TIMES+=1;
			if(_this.LEFT_CLICK_TIMES>=2 ){
				if(_this.success){
					_this.positions.pop();
					_this.success(_this.getLnlas());
				}
				_this.stop();
			}
		}
    },Cesium.ScreenSpaceEventType.LEFT_CLICK)
    this.handler.setInputAction(function (movement) {
    	if (_this.LEFT_CLICK_TIMES == 0){
    		_this.tip.showAt(movement.endPosition,"单击开始绘制，右键退出");
    	}else{
    		_this.tip.showAt(movement.endPosition,"单击结束绘制，右键退出");
    	}
    	if(_this.LEFT_CLICK_TIMES > 0){
    		let cartesian3=VFG.Util.getScreenToC3 (_this.viewer, movement.endPosition, _this.enity) 
            if(Cesium.defined(cartesian3)){
            	_this.positions.pop();
            	_this.positions.push(cartesian3);
            }
    	}
    	if(_this.positions.length >= 2){
			if(!_this.entity){
	            _this.createEntity();
			}
		}
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
	this.handler.setInputAction(function (movement) {
		_this.destroy();
	}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
},

VFG.DrawCircle.prototype.addListener=function(type,callback){
	if('success'==type){
		this.success=callback;
	}
	if('error'==type){
		this.error=callback;
	}
	if('finish'==type){
		this.finish=callback;
	}
}

VFG.DrawCircle.prototype.removeListener=function(type){
	if('success'==type){
		this.success=null;
	}
	if('error'==type){
		this.error=null;
	}
	if('finish'==type){
		this.finish=null;
	}
}

VFG.DrawCircle.prototype.createEntity=function(){
	var _this=this;
	var geodesic = new Cesium.EllipsoidGeodesic();
	this._callbackProperty=function(){
        var satrt = Cesium.Cartographic.fromCartesian(_this.positions[0]);
        var end = Cesium.Cartographic.fromCartesian(_this.positions[_this.positions.length-1]);                   
        geodesic.setEndPoints(satrt, end);
        return geodesic.surfaceDistance.toFixed(3)*1
	};
	
	_this.entity =_this.viewer.entities.add({
		id:VFG.Util.getUuid(),
		position:_this.positions[0],
/*		point: {
           color: Cesium.Color.YELLOW,
           pixelSize: 5,
        },*/
		ellipse:{
        	semiMajorAxis:new Cesium.CallbackProperty(_this._callbackProperty, false),
        	semiMinorAxis:new Cesium.CallbackProperty(_this._callbackProperty, false),
            material: Cesium.Color.RED.withAlpha(0.4),
            outline: true,
            outlineColor: Cesium.Color.YELLOW,
            outlineWidth:2,
        }
    });
}

VFG.DrawCircle.prototype.stop = function() {
    if( this.handler){
    	this.handler.destroy();
    	this.handler = null;
    };
    if(this.tip){
    	this.tip.destroy();
    }
};

VFG.DrawCircle.prototype.getLnlas = function() {
	return [VFG.Util.getC3ToLnLa(this.viewer,this.positions[0]),VFG.Util.getC3ToLnLa(this.viewer,this.positions[1])];
};

VFG.DrawCircle.prototype.destroy = function() {
	if(this.finish){
		this.finish();
	}
    if( this.handler){
    	this.handler.destroy();
    	this.handler = null;
    };
    if(this.tip){
    	this.tip.destroy();
    }
	if(this.entity){
		this.viewer.entities.remove(this.entity);
	}
	this._callbackProperty=null;
	delete this.entity;
	delete this.tip;
	delete this._callbackProperty;
	delete this.handler;
    delete this.viewer;
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="EPolyline.js" />
VFG.EPolyline = function(viewer, options) {
	this.viewer = viewer;
	this.options = options;
	this.parentId = options.parentId || '';
	this.id = options.id;
	this.name = options.name || '';
	this.code = options.code || '';
	this.type = options.type || '';
	this.thing = options.thing || {};
	this.attribute = options.attribute || {};
	this.propertys = options.propertys || [];
	this.init();
}
VFG.EPolyline.prototype.init = function() {
	let _this = this;
	this.entity = this.viewer.entities.add({
		id : this.id,
		name : this.name,
		code : this.code,
		type : this.type,
		polyline : {
			positions : this.thing.positions,
			material : this.getMaterial(),
			arcType : this.getArcType(),
			width : this.thing.width || 1,
			classificationType : this.getClassificationType(),
			distanceDisplayCondition : this.getDistanceDisplayCondition(),
		}
	});
};

VFG.EPolyline.prototype.updateWidth = function(width) {
	let _this = this;
	this.thing.width=width;
	if(this.entity){
		this.entity.polyline.width=this.thing.width;
	}
};

VFG.EPolyline.prototype.updateName = function(name) {
	let _this = this;
	this.name=name;
};

VFG.EPolyline.prototype.updateCode = function(code) {
	let _this = this;
	this.code=code;
};

VFG.EPolyline.prototype.getMaterial = function() {
	if ('line' == this.thing.materialType) {
		return this.thing.color ? Cesium.Color
				.fromCssColorString(this.thing.color) : Cesium.Color.RED
	} else if ('glow' == this.thing.materialType) {
		return new Cesium.PolylineGlowMaterialProperty({
			glowPower : this.thing.glowPower || 0.2,
			taperPower : this.thing.taperPower || 0.5,
			color : this.thing.color ? Cesium.Color
					.fromCssColorString(this.thing.color) : Cesium.Color.RED,
		})
	} else if ('outline' == this.thing.materialType) {
		return new Cesium.PolylineOutlineMaterialProperty({
			color : this.thing.color ? Cesium.Color
					.fromCssColorString(this.thing.color) : Cesium.Color.RED,
			outlineWidth : this.thing.outlineWidth || 2,
			outlineColor : this.thing.outlineColor ? Cesium.Color
					.fromCssColorString(this.thing.outlineColor)
					: Cesium.Color.BLACK,
		})
	} else if ('dash' == this.thing.materialType) {
		return new Cesium.PolylineDashMaterialProperty({
			color : this.thing.color ? Cesium.Color
					.fromCssColorString(this.thing.color) : Cesium.Color.RED,
			dashLength:this.thing.dashLength||16.0,
			dashPattern:this.thing.dashPattern||255.0,
			gapColor:this.thing.gapColor ? Cesium.gapColor
					.fromCssColorString(this.thing.gapColor) : Cesium.Color.TRANSPARENT
		})
	} else if ('arrow' == this.thing.materialType) {
		return new Cesium.PolylineArrowMaterialProperty(
				this.thing.color ? Cesium.Color
						.fromCssColorString(this.thing.color)
						: Cesium.Color.RED);
	} else {
		return this.thing.color ? Cesium.Color
				.fromCssColorString(this.thing.color) : Cesium.Color.RED
	}
}

VFG.EPolyline.prototype.updatePositions = function(positions, isDynamic) {
	let _this = this;
	if (positions) {
		this.thing.positions = positions;
		if (this.entity) {
			if (isDynamic) {
				if(!(this.entity.polyline.positions instanceof Cesium.CallbackProperty)){
					this.entity.polyline.positions = new Cesium.CallbackProperty(
						function(time) {
							return _this.thing.positions
						}, false)
				}
			} else {
				this.entity.polyline.positions = _this.thing.positions
			}
		}
	}
}

/**
 * clampToGround
 */
VFG.EPolyline.prototype.updateClampToGround = function(clampToGround) {
	let _this = this;
	if (clampToGround) {
		this.thing.clampToGround = clampToGround;
		if (this.entity) {
			if ('1' == this.thing.clampToGround) {
				this.entity.polyline.clampToGround = true
			} else {
				this.entity.polyline.clampToGround = false
			}
		}
	}
}

VFG.EPolyline.prototype.getArcType = function() {
	if ('GEODESIC' == this.thing.arcType) {
		return Cesium.ArcType.GEODESIC;
	} else if ('NONE' == this.thing.arcType) {
		return Cesium.ArcType.NONE;
	} else if ('RHUMB' == this.thing.arcType) {
		return Cesium.ArcType.RHUMB;
	} else {
		return Cesium.ArcType.GEODESIC;
	}
}

VFG.EPolyline.prototype.getClassificationType = function() {
	if ('BOTH' == this.thing.classificationType) {
		return Cesium.ClassificationType.BOTH;
	} else if ('CESIUM_3D_TILE' == this.thing.classificationType) {
		return Cesium.ClassificationType.CESIUM_3D_TILE;
	} else if ('TERRAIN' == this.thing.classificationType) {
		return Cesium.ClassificationType.TERRAIN;
	} else {
		return Cesium.ClassificationType.BOTH;
	}
}

VFG.EPolyline.prototype.getDistanceDisplayCondition = function() {
	if('1'==this.thing.isDistanceDisplay){
		if (this.thing.distanceDisplayNear && this.thing.distanceDisplayFar) {
			return new Cesium.DistanceDisplayCondition(
					this.thing.distanceDisplayNear || 0.0,
					this.thing.distanceDisplayFar || Number.MAX_VALUE);
		}
	}
	return undefined
}

VFG.EPolyline.prototype.updateMaterial = function(material) {
	
	if(material.materialType){
		this.thing.materialType=material.materialType;
	}
	if(material.color){
		this.thing.color=material.color;
	}
	if(material.glowPower){
		this.thing.glowPower=material.glowPower;
	}
	if(material.taperPower){
		this.thing.taperPower=material.taperPower;
	}
	if(material.outlineWidth){
		this.thing.outlineWidth=material.outlineWidth;
	}
	if(material.outlineColor){
		this.thing.outlineColor=material.outlineColor;
	}
	if(material.outlineColor){
		this.thing.outlineColor=material.outlineColor;
	}
	if(material.dashLength){
		this.thing.dashLength=material.dashLength;
	}
	if(material.dashPattern){
		this.thing.dashPattern=material.dashPattern;
	}
	if(material.gapColor){
		this.thing.gapColor=material.gapColor;
	}
	if(this.entity){
		this.entity.polyline.material=this.getMaterial();
	}
}

VFG.EPolyline.prototype.updateClassificationType = function(classificationType) {
	this.thing.classificationType=classificationType;
	if(this.entity){
		this.entity.polyline.classificationType=this.getClassificationType();
	}
}

VFG.EPolyline.prototype.updateArcType = function(arcType) {
	this.thing.arcType=arcType;
	if(this.entity){
		this.entity.polyline.arcType=this.getArcType();
	}
}

VFG.EPolyline.prototype.updateDistanceDisplayCondition = function(near,far) {
	this.thing.arcType=arcType;
	if(near){
		this.thing.distanceDisplayNear=near;
	}
	if(far){
		this.thing.distanceDisplayFar=far;
	}
	if(this.entity){
		if('1'==this.thing.isDistanceDisplay){
			this.entity.polyline.distanceDisplayCondition=this.getDistanceDisplayCondition();
		}
	}
}

VFG.EPolyline.prototype.isDistanceDisplay = function(isDistanceDisplay) {
	this.thing.isDistanceDisplay=isDistanceDisplay;
	if(this.entity){
		if('1'==this.thing.isDistanceDisplay){
			this.entity.polyline.distanceDisplayCondition=this.getDistanceDisplayCondition();
		}else{
			this.entity.polyline.distanceDisplayCondition=undefined;
		}
	}
}


VFG.EPolyline.prototype.updateProperty= function(property) {
	var _this = this;
	if(_this.propertys){
		for(let index in _this.propertys){
			if(property.id==_this.propertys[index].id){
				_this.propertys.splice(index,1,property);
				return;
			}
		}
		_this.propertys.push(property);
	}
};

VFG.EPolyline.prototype.removeProperty= function(id) {
	var _this = this;
	if(_this.propertys){
		for(let index in _this.propertys){
			if(id==_this.propertys[index].id){
				_this.propertys.splice(index,1);
				return;
			}
		}
	}
};

VFG.EPolyline.prototype.destroy = function() {
	let _this = this;
	if (this.entity) {
		this.viewer.entities.remove(this.entity);
	}
	delete this.entity
	delete this.options
	delete this.thing
	delete this.viewer
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="ERoadMark.js" />
VFG.ERoadMark=function(viewer, options) {
	this.viewer = viewer;
	this.options = options;
	this.parentId= options.parentId||'';
	this.id= options.id;
	this.name= options.name||'';
	this.code= options.code||'';
	this.type= options.type||'';
	this.thing=options.thing||{};
	this.attribute=options.attribute||{};
	this.propertys=options.propertys||[];
	this.init();
}
VFG.ERoadMark.prototype.init = function() {
	let _this=this;
	this.entity= this.viewer.entities.add({
		id:this.id,
		name:this.name,
		code:this.code,
		type:this.type,
		position:this.getCenter(),
        rectangle : {
	       coordinates :Cesium.Rectangle.fromCartesianArray(_this.thing.coordinates),
		   rotation: Cesium.Math.toRadians(_this.thing.angle||0),
		   stRotation: Cesium.Math.toRadians(_this.thing.angle||0),
	       material :	_this.getMaterial(),
	       heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
	    }
   });
};

VFG.ERoadMark.prototype.updateName = function(name) {
	this.name=name;
	if(this.entity){
		this.entity.name=this.name;
		this.entity.rectangle.material=this.getMaterial();
	}
}

VFG.ERoadMark.prototype.updateCode = function(code) {
	this.code=code;
	if(this.entity){
		this.entity.code=this.code;
	}
}

VFG.ERoadMark.prototype.updateFont = function(font) {
	this.thing.font=font;
	if(this.entity){
		this.entity.rectangle.material=this.getMaterial();
	}
}

VFG.ERoadMark.prototype.updateFontSize = function(fontSize) {
	this.thing.fontSize=fontSize;
	if(this.entity){
		this.entity.rectangle.material=this.getMaterial();
	}
}

VFG.ERoadMark.prototype.updateFontColor = function(fontColor) {
	this.thing.fontColor=fontColor;
	if(this.entity){
		this.entity.rectangle.material=this.getMaterial();
	}
}

VFG.ERoadMark.prototype.updateAngle = function(angle) {
	var _this = this;
	this.thing.angle=angle;
	if(this.entity){
		this.entity.rectangle.rotation=new Cesium.CallbackProperty(function () {
			return Cesium.Math.toRadians(_this.thing.angle||0);
		}, false);
		this.entity.rectangle.stRotation=new Cesium.CallbackProperty(function () {
			return Cesium.Math.toRadians(_this.thing.angle||0);
		}, false);
	}
}

VFG.ERoadMark.prototype.getMaterial = function() {
	var _this = this;
	return new Cesium.ImageMaterialProperty({
        image: _this.drawText(),
        transparent: true,
        color: Cesium.Color.WHITE
    });
}

VFG.ERoadMark.prototype.drawText = function() {
	let _this=this;
/*    let text = this.name;
    var c = document.createElement("canvas");
    let d = (""+text+"").length * ( this.thing.fontSize||14);
    c.width = d;
    c.height = ( this.thing.fontSize||20);
    let ctx = c.getContext("2d");
    ctx.fillStyle = (( this.thing.fontColor||"rgb(255,255,255)"));
    ctx.font = "bold " +( this.thing.fontSize||20)+"px sans-serif";
    ctx.textBaseline = 'hanging'; */
    
	var canvas = document.createElement("canvas");
	let context = canvas.getContext("2d");
	
	context.width = Cesium.Rectangle.computeWidth  (Cesium.Rectangle.fromCartesianArray(_this.thing.coordinates));
	context.height=Cesium.Rectangle.computeHeight (Cesium.Rectangle.fromCartesianArray(_this.thing.coordinates))
	 
    context.fillStyle = "red";  // 填充颜色为红色
    context.strokeStyle = "blue";  // 画笔的颜色
    context.font = "28px sans-serif";
    context.textBaseline = 'hanging';
    context.fillText(_this.name,0, 0);
    
    return  canvas
};

VFG.ERoadMark.prototype.getCenter = function() {
	var rectangle = this.thing.coordinates;
	var center = Cesium.Rectangle.center(rectangle);
	var adre = Cesium.Cartographic.toCartesian(center);
	return adre;
}

VFG.ERoadMark.prototype.updateCoordinates = function(coordinates,isDynamic) {
	let _this=this;
	if(coordinates){
		this.thing.coordinates=coordinates;
		if(this.entity){
			if(isDynamic){
				this.entity.rectangle.coordinates=new Cesium.CallbackProperty(function (time) {
					return Cesium.Rectangle.fromCartesianArray(_this.thing.coordinates)
				}, false)
			}else{
				this.entity.rectangle.coordinates=Cesium.Rectangle.fromCartesianArray(this.thing.coordinates)
			}
		}
	}
}

VFG.ERoadMark.prototype.destroy = function() {
	let _this=this;
	if(this.entity){
		this.viewer.entities.remove(this.entity);
	}
	delete this.entity
	delete this.options
	delete this.thing
    delete this.viewer
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="MeasureLength.js" />
VFG.MeasureLength = function(viewer) {
	this.viewer = viewer;
	this.positions = [];
	this.poly = null;
	this.distance = 0;
	this.cartesian = null;
	this.floatingPoint = [];
	this.enity;
	this.tip = new VFG.Tip(this.viewer);
	this.init();
}
VFG.MeasureLength.prototype.init = function() {
	let _this = this;
	this.handler = new Cesium.ScreenSpaceEventHandler(_this.viewer.scene.canvas);
	this.handler.setInputAction(function(movement) {
		_this.tip.showAt(movement.endPosition, "单击开始，右击结束");
		_this.cartesian = VFG.Util.getScreenToC3(_this.viewer, movement.endPosition, _this.enity);
		if (_this.positions.length >= 2) {
			if (!_this.poly) {
				_this.poly = _this.viewer.entities.add({
					name: '直线',
					polyline: {
						show: true,
						positions: _this.positions,
						material: new Cesium.PolylineGlowMaterialProperty({
                     		glowPower : 0.5,
                      		color : Cesium.Color.fromCssColorString('#ffff00'),
                 		}),
						//material: Cesium.Color.fromCssColorString('#ffff00'),
						width: 3,
						clampToGround: true
					}
				});
			} else {
				_this.positions.pop();
				_this.positions.push(_this.cartesian);
				_this.poly.polyline.positions = _this.update();
			}
			_this.distance = _this.getSpaceDistance(_this.positions);
			_this.tip.showAt(movement.endPosition, _this.distance + "米");
		}
	}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

	this.handler.setInputAction(function(movement) {
		_this.cartesian = VFG.Util.getScreenToC3(_this.viewer, movement.position, _this.enity);
		if (_this.positions.length == 0) {
			_this.positions.push(_this.cartesian.clone());
		}
		_this.positions.push(_this.cartesian);
		//在三维场景中添加Label
		_this.addLabel();
	}, Cesium.ScreenSpaceEventType.LEFT_CLICK);

	this.handler.setInputAction(function(movement) {
		//_this.positions.pop(); //最后一个点无效
		_this.addLabel();
		if(_this.success){
			_this.success();
		}
		_this.stop();
	}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

};

VFG.MeasureLength.prototype.addLabel = function() {
	var _this=this;
	_this.floatingPoint.push(_this.viewer.entities.add({
		name: '空间直线距离',
		position: _this.positions[_this.positions.length - 1],
		point: {
			pixelSize: 5,
			color: Cesium.Color.RED,
			outlineColor: Cesium.Color.WHITE,
			outlineWidth: 2,
		},
		label: {
			text: _this.distance + "米",
			font: '18px sans-serif',
			fillColor: Cesium.Color.GOLD,
			style: Cesium.LabelStyle.FILL_AND_OUTLINE,
			outlineWidth: 2,
			verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
			pixelOffset: new Cesium.Cartesian2(20, -20),
		}
	}));
}

VFG.MeasureLength.prototype.update = function() {
	var _this = this;
	return new Cesium.CallbackProperty(function() {
		return _this.positions;
	}, false);
}

VFG.MeasureLength.prototype.getSpaceDistance = function(positions) {
	var distance = 0;
	for (var i = 0; i < positions.length - 1; i++) {

		var point1cartographic = Cesium.Cartographic.fromCartesian(positions[i]);
		var point2cartographic = Cesium.Cartographic.fromCartesian(positions[i + 1]);
		/**根据经纬度计算出距离**/
		var geodesic = new Cesium.EllipsoidGeodesic();
		geodesic.setEndPoints(point1cartographic, point2cartographic);
		var s = geodesic.surfaceDistance;
		//console.log(Math.sqrt(Math.pow(distance, 2) + Math.pow(endheight, 2)));
		//返回两点之间的距离
		s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic.height, 2));
		distance = distance + s;
	}
	return distance.toFixed(2);
}

VFG.MeasureLength.prototype.addListener=function(callback){
	if(callback!=null){
		this.success=callback;
	}
}

VFG.MeasureLength.prototype.removeListener=function(){
	this.success=null;
}

VFG.MeasureLength.prototype.stop = function() {
	if (this.tip) {
		this.tip.destroy();
	}
	if (this.handler) {
		this.handler.destroy();
		this.handler = null;
	};
}

VFG.MeasureLength.prototype.destroy = function() {
	var _this = this;
	if (this.tip) {
		this.tip.destroy();
	}
	if (this.handler) {
		this.handler.destroy();
		this.handler = null;
	};
	if (this.poly) {
		this.viewer.entities.remove(this.poly);
	}
	if (this.floatingPoint && _this.floatingPoint.length>0) {
		for(var i = 0; i < _this.floatingPoint.length; i++) {
			this.viewer.entities.remove(_this.floatingPoint[i]);
		}
	}
	delete this.poly
	delete this.floatingPoint
	delete this.handler
	delete this.viewer
};;
///<jscompress sourcefile="MeasureArea.js" />
VFG.MeasureArea = function(viewer) {
	this.viewer = viewer;
	this.positions = [];
	this.tempPoints = [];
	this.polygon = null;
	this.cartesian = null;
	this.areaLabel=null;
	this.floatingPoint = [];
	this.enity;
	this.tip = new VFG.Tip(this.viewer);
	this.radiansPerDegree = Math.PI / 180.0;//角度转化为弧度(rad) 
    this.degreesPerRadian = 180.0 / Math.PI;//弧度转化为角度
	this.init();
}
VFG.MeasureArea.prototype.init = function() {
	let _this = this;
	this.handler = new Cesium.ScreenSpaceEventHandler(_this.viewer.scene.canvas);
	this.handler.setInputAction(function(movement) {
		_this.tip.showAt(movement.endPosition, "单击开始，右击结束");
		_this.cartesian = VFG.Util.getScreenToC3(_this.viewer, movement.endPosition, _this.enity);
		if (_this.positions.length >= 2) {
			if (!_this.polygon) {
				_this.polygon = _this.viewer.entities.add({
					name: '直线',
					polygon: {
						hierarchy: [],
						//material: Cesium.Color.GREEN.withAlpha(0.5),
						material: Cesium.Color.fromCssColorString('#ffff00').withAlpha(0.5),
						classificationType: Cesium.ClassificationType.BOTH,
					}
				});
			} else {
				_this.positions.pop();
				_this.positions.push(_this.cartesian);
				_this.polygon.polygon.hierarchy = _this.update();
			}
			_this.tip.showAt(movement.endPosition, '单击拾取点，右击结束');
		}
	}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

	this.handler.setInputAction(function(movement) {
		_this.cartesian = VFG.Util.getScreenToC3(_this.viewer, movement.position, _this.enity);
		if (_this.positions.length == 0) {
			_this.positions.push(_this.cartesian.clone());
		}
		_this.positions.push(_this.cartesian);

		var cartographic = Cesium.Cartographic.fromCartesian(_this.positions[_this.positions.length - 1]);
		var longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
		var latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
		var heightString = cartographic.height;
		_this.tempPoints.push({ lon: longitudeString, lat: latitudeString, hei: heightString });
		//在三维场景中添加Label
		_this.addPoint();
	}, Cesium.ScreenSpaceEventType.LEFT_CLICK);

	this.handler.setInputAction(function(movement) {
		//_this.positions.pop(); //最后一个点无效
		_this.stop();
		_this.addPoint();
		_this.addLabel();
		if(_this.success){
			_this.success();
		}
	}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

};

VFG.MeasureArea.prototype.update = function() {
	var _this = this;
	return new Cesium.CallbackProperty(function() {
		return new Cesium.PolygonHierarchy(_this.positions);
	}, false);
}

VFG.MeasureArea.prototype.addLabel = function() {
	var _this = this;
	var textArea = _this.getArea(_this.tempPoints) + "平方公里";
	_this.areaLabel = _this.viewer.entities.add({
		name: '多边形面积',
		position: _this.positions[_this.positions.length - 1],
		label: {
			text: textArea,
			font: '18px sans-serif',
			fillColor: Cesium.Color.GOLD,
			style: Cesium.LabelStyle.FILL_AND_OUTLINE,
			outlineWidth: 2,
			verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
			pixelOffset: new Cesium.Cartesian2(20, -40),
			heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
		}
	});
}

VFG.MeasureArea.prototype.addPoint = function() {
	var _this = this;
	_this.floatingPoint.push(_this.viewer.entities.add({
		name: '多边形面积',
		position: _this.positions[_this.positions.length - 1],
		point: {
			pixelSize: 5,
			color: Cesium.Color.RED,
			outlineColor: Cesium.Color.WHITE,
			outlineWidth: 2,
			heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
		}
	}));
}

VFG.MeasureArea.prototype.getArea = function(points) {
	var _this = this;
	var res = 0;
	//拆分三角曲面
	for (var i = 0; i < points.length - 2; i++) {
		var j = (i + 1) % points.length;
		var k = (i + 2) % points.length;
		var totalAngle = _this.angle(points[i], points[j], points[k]);
		var dis_temp1 = _this.distance(_this.positions[i], _this.positions[j]);
		var dis_temp2 = _this.distance(_this.positions[j], _this.positions[k]);
		res += dis_temp1 * dis_temp2 * Math.abs(Math.sin(totalAngle));
	}
	return (res / 1000000.0).toFixed(4);
}

/*角度*/
VFG.MeasureArea.prototype.angle = function(p1, p2, p3) {
	var _this = this;
	var bearing21 = _this.bearing(p2, p1);
	var bearing23 = _this.bearing(p2, p3);
	var angle = bearing21 - bearing23;
	if (angle < 0) {
		angle += 360;
	}
	return angle;
}

/*方向*/
VFG.MeasureArea.prototype.bearing = function(from, to) {
	var _this = this;
	var lat1 = from.lat * _this.radiansPerDegree;
	var lon1 = from.lon * _this.radiansPerDegree;
	var lat2 = to.lat * _this.radiansPerDegree;
	var lon2 = to.lon * _this.radiansPerDegree;
	var angle = -Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2), Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2));
	if (angle < 0) {
		angle += Math.PI * 2.0;
	}
	angle = angle * _this.degreesPerRadian;//角度
	return angle;
}

VFG.MeasureArea.prototype.distance = function(point1, point2) {
	var point1cartographic = Cesium.Cartographic.fromCartesian(point1);
	var point2cartographic = Cesium.Cartographic.fromCartesian(point2);
	var geodesic = new Cesium.EllipsoidGeodesic();
	geodesic.setEndPoints(point1cartographic, point2cartographic);
	var s = geodesic.surfaceDistance;
	s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic.height, 2));
	return s;
}

VFG.MeasureArea.prototype.addListener=function(callback){
	if(callback!=null){
		this.success=callback;
	}
}

VFG.MeasureArea.prototype.removeListener=function(){
	this.success=null;
}

VFG.MeasureArea.prototype.stop = function() {
	if (this.tip) {
		this.tip.destroy();
	}
	if (this.handler) {
		this.handler.destroy();
		this.handler = null;
	};
}

VFG.MeasureArea.prototype.destroy = function() {
	var _this = this;
	if (this.tip) {
		this.tip.destroy();
	}
	if (this.handler) {
		this.handler.destroy();
		this.handler = null;
	};
	if(this.areaLabel){
		this.viewer.entities.remove(this.areaLabel);
	}
	if (this.polygon) {
		this.viewer.entities.remove(this.polygon);
	}
	if (this.floatingPoint && _this.floatingPoint.length > 0) {
		for (var i = 0; i < _this.floatingPoint.length; i++) {
			this.viewer.entities.remove(_this.floatingPoint[i]);
		}
	}
	delete this.polygon
	delete this.areaLabel
	delete this.floatingPoint
	delete this.handler
	delete this.viewer
	delete this.tempPoints
	delete this.cartesian
};;
///<jscompress sourcefile="PlanRoam.js" />
/**
 *Creates an instance of Roaming.
 * @param {*} viewer 需要传入
 * @param {*} options.modeluri 模型的uri 需要传入
 * @param {*} options.time 漫游时间  需要传入
 * @param {*} options.points  点集合 需要传入
 * @param {*} options.isPathShow 路径是否显示 需要传入
 * @memberof Roaming
 */
VFG.PlanRoam = function(viewer,options) {
	this.options = options;
	this.viewer = viewer;
	this.entity = undefined;
	this.start = undefined;
	this.stop = undefined;
	this.map = new Map;
	this.index = 0;
	this.modeluri = options.modeluri ? options.modeluri : undefined;
	this.isLock = options.isLock ? options.isLock : false;
	this.time = options.duration; //传入飞行时间
	this.lines = options.lines;
	this.points = []; //传入漫游点位
	this.getLnLaFormC3();
	this.length = this.getTotalLength(this.points); //计算线路长度
	this.speed = this.length / this.time; //计算飞行速度
	this.startPoint = this.points[0];
	this.stopPoint = this.points[1];
	this.isPathShow = options.isPathShow ? options.isPathShow : false;
	this.property = this.GetRoamingLineProperty();
	this.InitRoaming();
}

VFG.PlanRoam.prototype.flyToPoisition = function(position) {
	if(position){
		this.viewer.camera.flyTo({//定位到范围中心点
			  destination: Cesium.Cartesian3.fromDegrees(position.x*1, position.y*1,(position.z*1)+1000),
			  orientation: {
			     heading: Cesium.Math.toRadians(180),//1
			     pitch: Cesium.Math.toRadians(-90),
			     roll: 0
			  }
		});
	}
}

/**
 * 坐标转换
 */
VFG.PlanRoam.prototype.getLnLaFormC3 = function(){
	let _this=this;
	if(this.lines && this.lines.length>0){
		for (let p of this.lines) {
			let point = VFG.Util.getLnLaFormC3(_this.viewer,p);
			if(point){
				_this.points.push(point);
			}
		}
	}
}

/**
 * 计算2点距离
 */
VFG.PlanRoam.prototype.getLength = function(startPoint, stopPoint) {
	let linePoint = [];
	linePoint.push([startPoint.x * 1, startPoint.y * 1]);
	linePoint.push([stopPoint.x * 1, stopPoint.y * 1]);
	return turf.length(turf.lineString(linePoint), {
		units: 'kilometers'
	});
}
/**
 * 计算多个点位总长度
 */
VFG.PlanRoam.prototype.getTotalLength = function(points) {
	let linePoint = [];
	for (let point of points) {
		let item = [];
		item.push(point.x * 1);
		item.push(point.y * 1);
		linePoint.push(item);
	}
	if (linePoint.length > 0) {
		let line = turf.lineString(linePoint);
		return turf.length(line, {
			units: 'kilometers'
		});
	}
	return 0;
}
VFG.PlanRoam.prototype.GetRoamingLineProperty = function(startPoint, endPoint) {
	let property = new Cesium.SampledPositionProperty();
	let lineLength = this.points.length;
	let start = Cesium.JulianDate.now()
	this.start = start;
	let stop = Cesium.JulianDate.addSeconds(start, this.time, new Cesium.JulianDate());
	this.stop = stop;
	this.viewer.clock.startTime = start.clone();
	this.viewer.clock.stopTime = stop.clone();
	this.viewer.clock.currentTime = start.clone();
	this.viewer.clock.clockRange = Cesium.ClockRange.CLAMPED; // Loop at the end
	this.viewer.clock.multiplier = 10;
	this.viewer.clock.onStop.addEventListener(this.options.complete);
	let time = Cesium.JulianDate.addSeconds(start, 0, new Cesium.JulianDate());
	let j=0;
	for (i = 0; i < lineLength; i++) {
		if(i>0)
		time = Cesium.JulianDate.addSeconds(start, j+=(this.time/lineLength), new Cesium.JulianDate());
		property.addSample(time, Cesium.Cartesian3.fromDegrees(this.points[i].x, this.points[i].y, this.points[i].z));
	}
	return property;
}
/**
 * 计算时间
 */
VFG.PlanRoam.prototype.ComputeTime = function(point1, point2) {
	let linePoint = [];
	linePoint.push([point1.x * 1, point1.y * 1]);
	linePoint.push([point2.x * 1, point2.y * 1]);
	let line = turf.lineString(linePoint);
	return turf.length(line, {
		units: 'kilometers'
	}) / this.speed;
}

/**
 * @param {*} 运行
 * @memberof Roaming
 */
VFG.PlanRoam.prototype.InitRoaming = function() {
	var _this = this;
	var position = _this.property;
	this.entity = this.viewer.entities.add({
		availability: new Cesium.TimeIntervalCollection([new Cesium.TimeInterval({
			start: this.start,
			stop: this.stop
		})]),
		position: position,
		orientation: new Cesium.VelocityOrientationProperty(position),
		point: {
			pixelSize: 10,
			color: Cesium.Color.YELLOW
		},
		path: {
			resolution: 1,
			material: new Cesium.PolylineGlowMaterialProperty({
				glowPower: 0.1,
				color: Cesium.Color.YELLOW
			}),
			width: 10,
			show: this.isPathShow
		}
	})
	this.entity.position.setInterpolationOptions({ // 点插值
		interpolationDegree: 5,
		interpolationAlgorithm: Cesium.LinearApproximation
	});
	this.flyToPoisition(_this.points[0]);
	this.viewer.clock.shouldAnimate = false;
	this.viewer.trackedEntity = this.entity;
}
/**
 * 开始巡检
 */
VFG.PlanRoam.prototype.StartRoaming = function() {
	this.viewer.clock.shouldAnimate = true;
	this.viewer.clock.onStop.addEventListener(this.OnStopRoaming, this);
	this.viewer.clock.shouldAnimate = true;
}
VFG.PlanRoam.prototype.OnStopRoaming = function(e) {
	let _this = this;
	this.viewer.clock.shouldAnimate = false;
	_this.viewer.clock.onStop.removeEventListener(_this.OnStopRoaming, this);
	if (_this.options.complete) {
		_this.options.complete(this);
	}
}
/**
 *漫游的暂停和继续
 * @param {*} state bool类型 false为暂停，ture为继续
 * @memberof Roaming
 */
VFG.PlanRoam.prototype.PauseOrContinue = function(state) {
	this.viewer.clock.shouldAnimate = state;
}
/**
 *改变飞行的速度
 * @param {*} value  整数类型
 * @memberof Roaming
 */
VFG.PlanRoam.prototype.ChangeRoamingSpeed = function(value) {
	this.viewer.clock.multiplier = value;
}

/**
 *取消漫游
 * @memberof Roaming
 */
VFG.PlanRoam.prototype.EndRoaming = function() {
	if (this.entity !== undefined) {
		this.viewer.clock.shouldAnimate = false;
		this.viewer.clock.onStop.removeEventListener(this.OnStopRoaming);
		this.viewer.entities.remove(this.entity);
	}
}

VFG.PlanRoam.prototype.destroy = function() {
	let _self = this;
	_self.EndRoaming();
	return Cesium.destroyObject(_self);
};
